File opening error. The global symbol "$ infilename" requires an explicit package name
I am writing my first perl script and am unable to compile it. I want to read in a file and output every line that matches the regex criteria for a new file. I am getting a "global symbol requires an explicit package name" error, which seems to be related to variable scope issues from what I was reading. However, I cannot figure out what happened to my code.
code:
#!/usr/bin/perl -w
use strict;
use warnings;
print "Stripping lines from data dump where WREN column is FFF\n"
my $infilename = "./test_in.txt";
my $outfilename = "./test_out.txt";
my $in = undef;
open($in, "<", $infilename) or die "Can't open $infilename: $!";
open(my $out, ">", $outfilename) or die "Can't open $outfilename: $!";
while (<$in>) { # assigns each line in turn to $_
if (/.{73}FFF/){
print $out $_;
}
}
Error message:
syntax error at strip_nonwrites.pl line 8, near "my "
Global symbol "$infilename" requires explicit package name at strip_nonwrites.pl line 8.
Global symbol "$infilename" requires explicit package name at strip_nonwrites.pl line 12.
Global symbol "$infilename" requires explicit package name at strip_nonwrites.pl line 12.
Execution of strip_nonwrites.pl aborted due to compilation errors.
source to share
It is not unusual for a single syntax error to flush the parser enough to cause many false errors after the fact. This is such a case.
The first mistake is your first mistake. You are missing the semicolon at the end of line 6 ( near "my "
on line 8
).
All the "Global symbol ..." errors are just confusion created by trying to parse lines 6..8 as one command.
source to share
As you read, there is print
no semicolon at the end of the first statement . Later error messages will depend on what Perl refused to do from your faulty script, and are often unreliable.
Some other points
-
You should
use warnings
give preference-w
to the command line or the shebang line. Both are wrong at once. -
No need for a master file
./
for data files. This only applies when running an executable from a shell when PATH is looking for a filename if no path is specified -
You should declare your lexical variables as late as possible in your program. In the case of file descriptors that are inside the call
open
, as you did with$out
-
The operator
select
allows you to write subsequent callsprint
without specifying a file descriptor -
It is probably better to use
substr
orunpack
to extract fixed position substrings from each record
This leaves a program that looks like this:
#!/usr/bin/perl
use strict;
use warnings;
print "Stripping lines from data dump where WREN column is FFF\n";
my ($infilename, $outfilename) = qw/ test_in.txt test_out.txt /;
open my $in_fh, '<', $infilename or die qq{Can't open "$infilename" for input: $!};
open my $out_fh, '<', $outfilename or die qq{Can't open "$outfilename" for output: $!};
select $out_fh;
while ( <$in_fh> ) {
print if substr($_, 73, 3) eq 'FFF';
}
source to share