I'm going to answer that. But first, an introduction. Run these chunks of code as separate programs.
"japhy" =~ /a/;
eval q{ print $& };
The above code prints nothing.
"japhy" =~ /a./;
eval q{ print $& };
The above code prints "ap".
"japhy" =~ /a/;
print $&;
The above code prints "a".
Confused yet?
Here's the worst part:
@& = (1,2,3);
"japhy" =~ /a/;
eval q{ print $& };
That code prints "a".
From the above examples, you should extract some things:
- some regexes don't set $&
- other regexes do
- if Perl sees you use $&, it'll set $& all the time
- if Perl sees you use ANY variable named &, it'll set $& all the time
So what's going on? Well, the regex
/a/ is too simple to be a regex, so Perl does a Boyer-Moore search instead. But the regex
/a./ isn't a BM-type search, so it's a regex. And as long as it really goes through the regex engine, Perl sets up the
$& functionality.
But if Perl sees you using $&, it makes everything that looks like a regex act like a regex, and set up the $& functionality. Bah. That's irritating, and "bad".
This just in: I patched gv.c so that only $& sets the PL_sawampersand flag to a true value. Now you can use @& without worry.
_____________________________________________________
Jeff[japhy]Pinyan:
Perl,
regex,
and perl
hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.