Trivial perl doubt about FILE

Hi,

In the following perl code:

#!/usr/bin/perl -w

if (open(FILE, "< in_file")) {
    while (<FILE>) {
        chomp($_);
        if ($_ =~ /patt$/) {
            my $f = (split(" ", $_))[0];
            print "$f\n";
        }
    }
    close FILE;
}

Why changing the "FILE" as "$FILE" gives error in the while loop and in the close statement?

Which error, and did you change it everywhere?

FILE is the name of the file handle,
in_file is the name of the file you are trying to read.

I think you may be mistaking Perl for Bash, the variable $FILE is always $FILE and is a different thing to the file handle FILE, best practice these days suggests that you should open files with lexically scoped file handles (and the 3 argument form of open) so you should never see a bareword like FILE in your source.

if ( open( my $file, '<' , 'in_file' ) ){
   while(<$file>){
...
1 Like

In the context in which you are using it FILE is what is known in Perl as a bareword.

A bareword is any combination of letters, numbers, and underscores, and is not qualified by any symbols. That is, while $dog is a scalar and @dog is an array, dog is a bareword.

There are a couple areas in Perl where a bareword is allowed, this being one of them.

1 Like