Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl warning: Use of uninitialized value in concatenation (.) or string

Tags:

regex

perl

I cannot figure out why the regex patterns are not matching. Also, the output complains that $found is not initialized, but I believe I did so. Here is my code so far:

use strict;
use warnings;

my @strange_list = ('hungry_elephant', 'dancing_dinosaur');

my $regex_patterns = qr/
    elephant$
    ^dancing
    /x;

foreach my $item (@strange_list) {
    my ($found) = $item =~ m/($regex_patterns)/i;
    print "Found: $found\n";
}

Here is the output I get:

Use of uninitialized value $found in concatenation (.) or string at C:\scripts\perl\sandbox\regex.pl line 13.
Found:
Use of uninitialized value $found in concatenation (.) or string at C:\scripts\perl\sandbox\regex.pl line 13.
Found:

Do I need to initialize $found in another manner? Also, am I correctly creating a multi-line string to be interpreted as regex?

Many thanks.

like image 965
Dirty Penguin Avatar asked Jul 08 '13 13:07

Dirty Penguin


1 Answers

If the pattern match (=~) doesn't match anything, nothing will be stored in your scalar $found so Perl is complaining that you are trying to interpolate a variable that wasn't given a value.

You can get around this easily by using the postfix unless conditional:

$found = "Nothing" unless $found
print "Found: $found\n";

The code above assigns the value "Nothing" to $found only if it does not already have a value. Now your print statement will always work correctly, in either case.

You could also just use a simple if statement, but that seems more verbose:

if( $found ) {
   print "Found: $found\n";
}
else {
   print "Not found\n";
}

Another option that might be the most clean, is to place your pattern match in the if statement:

if( my ($found) = $item =~ m/($regex_patterns)/i ) {
   # if here, you know for sure that there was a match
   print "Found: $found\n";
}
like image 67
Hunter McMillen Avatar answered Oct 01 '22 16:10

Hunter McMillen