[tpm] Pub discussion (2)

Alex Beamish talexb at gmail.com
Thu Aug 28 21:05:42 PDT 2008


Further to my last, there was some discussion that passing numbered
regexp parameters to a subroutine, and then doing a further regexp
would pollute $1 and cause its value to change.

My test code:

#!/usr/bin/perl -w
#
#  Another example. Does
#
#    t($1,$2)
#
#    sub t
#    {
#      my $a = shift;
#      m/(...)/;
#      return ($a);
#    }
#
#  mean that $a now contains the new value of $1 because there's a new $1
#  value?

use strict;

{
    my $line = "The quick brown fox jumped over ..";
    my ( $noun, $verb ) = ( $line =~ m/(\w+) (j\w+)/ );

    print "Noun is $noun, verb is $verb.\n";
    print "Noun is $1, verb is $2.\n";

    my $return = t($1, $2);
    print "The return value is $return.\n";
}

sub t
{
    my $abc = shift;
    my $foo = "This is the last line of the test.";
    my ( $prep ) = ( $foo =~ /(th\w)/ );
    print "OK, \$1 is $1 and abc is $abc.\n";

    #  Since the first parameter passed into this subroutine was $1, the
    #  hypothesis is that by collecting a new $1, we will overwrite the
    #  original value of $abc.

    return ( $abc );
}

Running this script produces

[alex at foo tpm-August2008]$ perl -w regexp.pl
Noun is fox, verb is jumped.
Noun is fox, verb is jumped.
OK, $1 is the and abc is fox.
The return value is fox.

I would say that the hypothesis is disproved, unless I've
misunderstood the example as it was presented to me. Corrections and
clarifications gladly welcomed.

-- 
Alex Beamish
Toronto, Ontario
aka talexb


More information about the toronto-pm mailing list