Kajal_T Kajal_T - 5 months ago 35
Perl Question

Perl Code Error: Global Symbol Requires explicit package name

I am trying to compile this code, but it keeps getting same error for @fields and $element variable. As far as I can tell it is not an scoping error, as it is declared globally. It gets compiled if I don't use strict.

I have provided a prototype of code, please ignore any typing errors.

#!usr/bin/perl
use strict;
use warnings;
use file::BaseName;
use file::Copy;

#my array declaration
my @fields;

#my other declarations
#input and output file initialization

while(<DATA1>) {
$String='';
$String= $_;
@fields= split(/,/,$String);
foreach my $elements(@fields){
#Some code
}

#more code
}
close (DATA1);

Answer

At a bare minimum, you need to get your code to compile. The perl compiler is usually very helpful in telling you what is wrong. Here you have invalid package names, an invalid perl path, and you should use DATA instead of DATA1.

Try running your code using diagnostics as it is more informative:

perl -cwT -Mdiagnostics script.pl

Can't locate file/BaseName.pm in @INC (you may need to install the
file::BaseName module) (@INC contains: /etc/perl /usr/local/lib/i386-
... ) at foo2.pl line 4.

BEGIN failed--compilation aborted at foo2.pl line 4 (#1)
    (F) You said to do (or require, or use) a file that couldn't be found.
    Perl looks for the file in all the locations mentioned in @INC, unless
    the file name included the full path to the file.  Perhaps you need
    to set the PERL5LIB or PERL5OPT environment variable to say where the
    extra library is, or maybe the script needs to add the library name
    to @INC.  Or maybe you just misspelled the name of the file.

    See "require" in perlfunc and lib.

Uncaught exception from user code:
    Can't locate file/BaseName.pm in @INC (you may need to install the
    file::BaseName module) (@INC contains: /etc/perl /usr/local/lib/i386-
    ... ) at foo2.pl line 4.

BEGIN failed--compilation aborted at foo2.pl line 4.

Here is a compiling version of your code:

#!/usr/bin/perl

use strict;
use warnings;
use File::Basename;
use File::Copy;

my @fields;

while(<DATA>) {
    my $String='';
    $String= $_;
    @fields= split(/,/,$String);
    my $i = 0;
    foreach my $element (@fields) {
        print "[$i] : $element\n";
        $i++;
    }
}

__DATA__
foo,bar,baz
qux,1,2,3

Output

[0] : foo
[1] : bar
[2] : baz

[0] : qux
[1] : 1
[2] : 2
[3] : 3
Comments