in reply to Can anyone tell me what is going on with my code?(Regex match variables)
G'day samh785,
The special variables $1, $2, etc. are reinitialized on each match. This includes matches done as part of a substitution. After '$mac1 =~ s/:/-/g;', which contains no captures, both $1 and $2 are uninitialized.
Here's a example:
#!/usr/bin/env perl -l use strict; use warnings; my $string = 'abc|def'; if ($string =~ /(\S{3})\|(\S{3})/) { print "After first match (in if condition): \$1=$1 \$2=$2"; my $whatever = 'blah'; $whatever =~ s/b/c/; print "After second match (in substitution): \$1=$1 \$2=$2"; }
Output:
After first match (in if condition): $1=abc $2=def Use of uninitialized value $1 in concatenation (.) or string at ./pm_1 +143443_match_vars.pl line 12. Use of uninitialized value $2 in concatenation (.) or string at ./pm_1 +143443_match_vars.pl line 12. After second match (in substitution): $1= $2=
Assigning $2 to $mac2 before attempting the substitution should fix your problem.
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Can anyone tell me what is going on with my code?(Regex match variables)
by samh785 (Initiate) on Sep 30, 2015 at 18:07 UTC | |
by AnomalousMonk (Archbishop) on Sep 30, 2015 at 19:55 UTC | |
by mr_ron (Deacon) on Sep 30, 2015 at 19:30 UTC |