开发者

Perl: Opening File

开发者 https://www.devze.com 2023-02-09 11:46 出处:网络
I am trying to open the file received as argument. When i store the argument in to the global variable open works successfully.

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 :ER开发者_开发技巧ROR: $!". "\n";


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.


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)


use strict;
use warnings;

my $file_name = shift @ARGV;
open(my $file, '<', $file_name) or die $!;
…
close($file);

Always use strict and warnings. If either of them complains, fix the code, do not comment out the pragmas. You can also use autodie to avoid the explicit or die after open, see autodie.


From Perl's docs for 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号