I have just started learning perl and I was going through filehandle.
I tried the below, but never worked:
#!/usr/bin/perl
$file = 'File.txt';
open ($fh, '>', $file) or die "Error :$!";
print "Enter blank line to end\n";
while (<STDIN>) {
last if /^$/;
print "FH: $fh \n";
print "dollar: $_ \n";
}
close $fh;*
The below works, but I don't understand why.
#!/usr/bin/perl
open(my $fh, '>', 'report.txt');
foreach my $line ( <STDIN> ) {
chomp( $line );
print $fh "$line\n";
}
close $fh;
print "done\n";
You have opened the filehandle $fh
for writing to your file. Your second example prints data to this filehandle, so it works:
print $fh "$line\n";
But your first example doesn't print to $fh
, so the output goes to STDOUT
.
print "FH: $fh \n";
print "dollar: $_ \n";
In order for your first example to work, you need to print to the correct filehandle.
print $fh "FH: $fh \n";
print $fh "dollar: $_ \n";