Ansh007
Ansh007

Reputation: 97

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

Upvotes: 0

Views: 1190

Answers (1)

Dave Cross
Dave Cross

Reputation: 69314

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

Upvotes: 4

Related Questions