Search code examples
perlglobal-variablessubroutine

Global Symbol requires package name while using "my" in Sub


I have a class where we are learning Perl so forgive me if I made a simple/obvious error as I am still learning. My question is why do I get the error

Global Symbol "%localhash" requires explicit package name

as well as the same error for "$param" when I do declare it with "my %localhash" the first time inside the Sub.

My code for reference:

use strict;
use warnings;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA=qw(Exporter);
@EXPORT=("insert_user", "modify_user", "remove_user", "generate_list");


#Insert user Function
Sub insert_user{
    my $param = shift;
    my %localhash = %$param;
    print "Please enter Username: ";
    my $user_name = <>;
    chomp($user_name);
    if(exists ($localhash{$user_name})){ 
        print "Error, user already exists!";
        last;
    }
    $user_name =~ s/[^a-zA-Z0-9]//g;
    $user_name = lc($user_name);
    $localhash{$user_name};
    return %localhash;
    print "Please enter a password: ";
    my $user_password = <>;
    %localhash{$user_name} = $user_password;
    return %localhash;
}

In my class we are suppose to use "my $param" and "my %localhash" various times so I would repeat the same process in declaring "my" in every Sub but I keep getting the same error as if the "my" is not there.


Solution

  • The first error you get is syntax error at foo.pl line 13, near "my "; getting a syntax error throws perl's parser off and you will often get spurious errors afterwards due to it not having successfully recognized a declaration or being mistaken about scope. Ignore them and fix the syntax error (which in this case is actually a couple lines earlier: Sub instead of sub, as pointed out by toolic). That will get you on to the next error :)

    Other comments:

    Using last as you do is bad; it will exit a loop, but there isn't a loop in your code. If your sub is called from within a loop, it will (with a warning) exit your sub and exit that loop, but that is the kind of action at a distance that leads to bugs.

    For a long time, Exporter hasn't needed to be subclassed; simply use Exporter 'import'; instead of setting @ISA.