hari
hari

Reputation: 1

printing the output of a derefrenced variable into a file

I had a written a module, just to bifurcate a file into training and test sets. The output is fine, but it would be really easy for the students if the output of the two referenced variables, @$test and @$training were redirected to two different files. Here is the code:

use Cut;

my($training,$test)=Cut::cut_80_20('data.csv') ;
print"======TRAINING======\n"."@$training\n";
print"======TEST==========\n"." @$test\n";

Upvotes: 0

Views: 100

Answers (2)

ysth
ysth

Reputation: 98433

print takes an optional filehandle before the data to output. Open your files and print away:

open( my $training_fh, '>', 'training.csv' ) or die "Couldn't open training.csv: $!";
print $training_fh "======TRAINING======\n"."@$training\n"; 
open( my $test_fh, '>', 'test.csv' ) or die "Couldn't open test.csv: $!";
print $test_fh "======TEST==========\n"." @$test\n";

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 755010

It's very easy:

open my $fh1, '>', "training.out" or die "failed to open training.out ($!)";
print $fh1 "======TRAINING======\n";
print $fh1 "@$training\n";
close $fh1;
open my $fh2, '>', "test.out" or die "failed to open test.out ($!)";
print $fh2 "======TEST==========\n";
print $fh2 "@$test\n";
close $fh2;

Note the absence of a comma after the file handle in the print statements. You can add newlines and such like as necessary.

Upvotes: 2

Related Questions