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

Hello! I have no ideas how to fix this error, saw some similar problems, however didn`t find the answer.

Here is the code:

my $funct = sub($) { my $var = shift; my $var2 = $var =~ /red|green|blue/; $var2 = 'magenta' if ($var eq 'm'); return $var2; };

Thanks!

Replies are listed 'Best First'.
Re: Use of uninitialized value $var in pattern match (m//)
by Corion (Patriarch) on Apr 10, 2015 at 10:38 UTC

    The error is pretty self-describing. $var contains undef. If you don't want undef to be passed to the invocation of $funct, you can find out where it is passed by using:

    use Carp 'croak'; my $funct= sub { my $var= shift; croak '$var was passed an uninitialized value' if not defined $var; ... };

    Note that the prototype on the subroutine won't help anything because a prototype only influences how Perl parses source code and Perl does not know where the value of $funct is used to call a function. I would leave the prototype off.

Re: Use of uninitialized value $var in pattern match (m//)
by Athanasius (Archbishop) on Apr 10, 2015 at 12:40 UTC

    Hello CropCircle, and welcome to the Monastery!

    This line:

    my $var2 = $var =~ /red|green|blue/;

    looks a bit strange to me. If $var contains 'xredy', for example, the match will succeed but $var2 will be set to 1 (“true”):

    22:35 >perl -wE "my $var = 'xredy'; my $var2 = $var =~ /red|green|blue +/; say qq[|$var2|];" |1| 22:35 >

    Is that really what you want? To set $var2 to the string that was matched, you need something like this:

    22:25 >perl -wE "my $var = 'xredy'; my ($var2) = $var =~ /(red|green|b +lue)/; say qq[|$var2|];" |red| 22:30 >

    The parentheses within the regex are for capturing, and the parentheses around $var put the match into list context. See perlretut#Extracting-matches. Or you can get the capture in $1:

    22:38 >perl -wE "my $var = 'xredy'; $var =~ /(red|green|blue)/; my $va +r2 = $1; say qq[|$var2|];" |red| 22:38 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks a lot!

Re: Use of uninitialized value $var in pattern match (m//)
by hippo (Archbishop) on Apr 10, 2015 at 10:37 UTC

    The code you have posted does not produce that warning.

    $ perl -w my $funct = sub($) { my $var = shift; my $var2 = $var =~ /red|green|blue/; $var2 = 'magenta' if ($var eq 'm'); return $var2; }; $
      Just compiling the sub ref will not produce that warning anyway. The sub ref needs to be actually called by some other code and executed to get an unitialized value warning.

      Je suis Charlie.