[H-GEN] A perl query

Jason Parker-Burlingham jasonp at uq.net.au
Mon May 5 14:10:01 EDT 2003


[ Humbug *General* list - semi-serious discussions about Humbug and     ]
[ Unix-related topics. Posts from non-subscribed addresses will vanish. ]

Three Blokes <gerbil at bigpond.net.au> writes:

> Jason Parker-Burlingham <jasonp at uq.net.au> wrote:
> >                 s/$regex/$subs{$1}/g;
> 
> One more clarification if you don't mind and then I will understand it all.
> In the above line, how does this expression know which value from %keys to
> substitute for the $regex that it's matched?,

That comes from the line that looks something like:

        $regex = "($regex)";    # put parentheses around $regex

Parens are special in regular expressions, they indicate that the
program should remember the substring that was matched by what's
inside.  The value is placed in the variable $1 (you can also refer to
it by the more standard regex notation \1), or, in list context, it's
returned by the =~ operator, which means you can do this:

        my ($star, $sidekick) = "Fred & Barney" =~ m/^(\w+)\W+(\w+)/;

which is essentially the same as

        if ("Fred & Barney" =~ m/^(\w+)\W+(\w+)/) {
                my $star = $1;
                my $sidekick = $2;
        }

> I'm assuming the {$1} is it, but what I want explained is how the
> compiler realises that $1 means the value that currently matches
> from $regex?,

I thought about writing the substitution like

        s/($regex)/$subs{$1}/g;

But I decided since $regex already had metacharacters (the unquoted
"|"s from the join a few lines up) that it might as well contain all
of them.  I can see now that it might've been clearer that way.

> is that just a standard (so in every case where a match is found $1
> will hold the value that was matched?

No, that's definitely *not* the case---if you want to save the matched
substring, you must use parentheses.

> Thanks again guys for all your help, and sorry to be a nuisance.

No problem.  You might want to treat yourself to a copy of Learning
Perl, 3rd Edition, when it is available in Australia.

jason, also if you find yourself doing lots of templating you might
       want to look into the Template Toolkit
-- 
``Oooh!  A gingerbread house!  Hansel and Gretel are set for life!''

--
* This is list (humbug) general handled by majordomo at lists.humbug.org.au .
* Postings to this list are only accepted from subscribed addresses of
* lists 'general' or 'general-post'.  See http://www.humbug.org.au/



More information about the General mailing list