Search code examples
perlstdinfilehandle

Writing STDIN to a file using filehandle in perl


I have just started learning perl and I was going through filehandle.

  1. I want to write my STDIN to a file. How do I do it using filehandle ?
  2. Also is it possible to do the same, without using FH ?

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"; 

Solution

  • 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";