nickm has asked for the wisdom of the Perl Monks concerning the following question:

My eval()s a code segment within a subroutine. The code it evals contains a subroutine, which I would think is completely local to the subroutine doing the eval. However the subroutine persists and I get a 'Subroutine redefined' warning whenever I call the eval more than once. See the code below. Main program is testeval.pl. It reads and evals code from testeval_code.pl
The main program = testeval.pl ########################################## #!/usr/bin/perl -w # call it twice to get the 'redfined' warning &testeval; &testeval; sub testeval { # read a replaceable code segment from a # file containing the evalsub subroutne my $code = read_replacable_code("testeval_code.pl"); eval $code; if ($@) { print "error eval $@\n"; } # call the sub defined in the eval'd code &evalsub; } sub read_replacable_code { my $fname = shift; $code = ''; if (open (FCODE, $fname)) { while (my $line = <FCODE>) { $code .= $line; } close (FCODE); } return $code; } the replacable code segment - testeval_code.pl ########################################## sub evalsub { print "evalsub\n"; } results ########################################## [root@mma-qa-be01 nick]# ./testeval.pl evalsub Subroutine evalsub redefined at (eval 2) line 2. evalsub

Replies are listed 'Best First'.
Re: Subroutine redefined error that I can't figure out
by Corion (Patriarch) on Apr 11, 2008 at 14:04 UTC

    Basically, subroutine names are global. Perl does not have locally nested subroutines.

    One possible way around it is to localize your changes to the symbol table:

    local *evalsub; eval $code; evalsub();

    Another way is to avoid using named subroutines and use code references:

    my $code = 'sub { print "evalsub" }'; my $coderef = eval $code; # Call our code $coderef->();
      local *evalsub works great and is the most flexible for my purpuses. Thanks for the help!
Re: Subroutine redefined error that I can't figure out
by Anonymous Monk on Apr 11, 2008 at 14:05 UTC
    subroutines are global, read perlsub
Re: Subroutine redefined error that I can't figure out
by apl (Monsignor) on Apr 11, 2008 at 14:13 UTC
    I made the $code in read_replacable_code local to that subroutine, and everything ran fine.