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.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With