Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Opening File

Tags:

perl

I am trying to open the file received as argument.

When i store the argument in to the global variable open works successfully.

But

If I use give make it as my open fails to open the file.

What is the reason.

#use strict;
use warnings;

#my $FILE=$ARGV[0];   #open Fails to open the file $FILE

$FILE=$ARGV[0];        #Works Fine with Global $FILE
open(FILE)
    or
die "\n ". "Cannot Open the file specified :ERROR: $!". "\n";
like image 787
vrbilgi Avatar asked Feb 08 '11 13:02

vrbilgi


2 Answers

Unary open works only on package (global) variables. This is documented on the manpage.

A better way to open a file for reading would be:

my $filename = $ARGV[0];           # store the 1st argument into the variable
open my $fh, '<', $filename or die $!; # open the file using lexically scoped filehandle

print <$fh>; # print file contents

P.S. always use strict and warnings while debugging your Perl scripts.

like image 50
Eugene Yarmash Avatar answered Nov 15 '22 07:11

Eugene Yarmash


It's all in perldoc -f open:

If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE contains the filename. (Note that lexical variables--those declared with "my"--will not work for this purpose; so if you're using "my", specify EXPR in your call to open.)

Note that this isn't a very good way to specify the file name. As you can see, it has a hard constraint on the variable type it's in, and either the global variable it requires or the global filehandle it opens are usually best avoided.

Using a lexical filehandle keeps its scope in control, and handles closing automatically:

open my $fh, '<', "filename" or die "string involving $!";

And if you're taking that file name from the command line, you could possibly do away with that open or any handle altogether, and use the plain <> operator to read from command-line arguments or STDIN. (see comments for more on this)

like image 33
JB. Avatar answered Nov 15 '22 09:11

JB.