Reputation: 11
In my current homework assignment, I am trying to open a file using the open or die condition. I am supposed to open a file, then list its contents line by line, and then apply a regex to it (this part is irrelevant right now). Here is some code so far...
my $filename = '<>';
open(my $fh, "<", $filename) or die "Could not open file, please enter a proper file handle";
while(<>){
print $_;
}
close $fh;
Thanks for helping guys... I look forward to an answer to my issue. I know it might be a simple answer but I'm still new to perl so anything is appreciated.
Upvotes: 0
Views: 519
Reputation: 385655
@ARGV
contains the program's arguments.
@ARGV == 1
or die("usage\n");
my ($qfn) = @ARGV;
open(my $fh, "<", $qfn)
or die("Can't open \"$qfn\": $!\n");
while (<$fh>) { # Sets $_
chomp; # Remove the line feed from $_.
print("$_\n"); # Re-adds the line feed and prints the line.
}
or
...
while ( my $line = <$fh> ) {
chomp($line); # Remove the line feed from $line.
print("$line\n"); # Re-adds the line feed and prints the line.
}
The thing is, Perl has a special handle (ARGV
) that reads from the files whose paths are found in @ARGV
(or from STDIN if not arguments were provided). This is the default handle used by <>
(meaning that <>
is short for <ARGV>
), so all you need is the following:
while (<>) {
chomp;
print("$_\n");
}
Technically, all you need is the following:
while (<>) {
print;
}
The above is equivalent to the following:
print while <>; # Also one line at a time.
You could even use the following:
print <>; # Reads all the lines, then prints them.
That said, one normally wants to transform the input in some way before printing it back out, and removing the training line feed is usually helpful to that.
I called the variable qfn for qualified file name, meaning a relative or absolute path that includes a file name. This is what you truly accept, rather than just a file name.
Upvotes: 2