Perl: Opening a file

I am trying to open a file received as an argument.

When I store the argument in a global variable, open works successfully.

But

If I use the make command, make sure my open cannot 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"; 
+6
perl
source share
4 answers

Unary open only works with batch (global) variables. This is described in the manpage .

The best way to open a file for reading:

 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 

PS always use strict and warnings when debugging your Perl scripts.

+13
source share

All this in perldoc -f open :

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

Please note that this is not a good way to specify a file name. As you can see, it has a strict restriction on the type of variable it is in, and usually needs the global variable that it requires, or the global file descriptor that it opens.

Using the lexical file descriptor saves its control area and closes automatically:

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

And if you take this file name from the command line, you can refuse this open or any descriptor altogether and use the simple <> operator to read from the command line arguments or STDIN. (see comments for more details)

+7
source share
 use strict; use warnings; my $file_name = shift @ARGV; open(my $file, '<', $file_name) or die $!; … close($file); 

Always use strict and warnings . If any of them complains, correct the code, do not comment on the pragmas. You can also use autodie avoid explicit or die after opening, see autodie .

+6
source share

From Perl docs to open ()

If EXPR is omitted, the scalar variable with the same name as FILEHANDLE contains the file name. (Note that lexical variables - those that were declared with mine - will not work for this purpose, so if you use mine, specify EXPR in your call to open.)

+3
source share

All Articles