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
    Makes sense and that fixed my issue. Thanks! A little upset that I forgot substituting would reset my values... :'(

      I find it's good practice to "capture" your capture variables immediately after a match even when you know for sure you will never be doing any further regex matching within that scope:

      if ($macs[1] =~ /(\S{17})\|(\S{17})/) { my ($mac1, $mac2) = ($1, $2); ... $mac1 =~ s/.../etc/g; $mac2 =~ s/as/needed/g; ... do_something_with($mac1, $mac2); ... }
      Just make this same, silly mistake as many times as I have and you'll never do otherwise!


      Give a man a fish:  <%-{-{-{-<

      Just a thought. Since you are only switching one character you could use y/// or tr/// instead of s/// and you would not overwrite your match/capture variables. Like: tr/:/-/.

      Ron