$&

created by premchai21
(thing) by premchai21 (1.9 wk) (print)   ?   (I like it!) 1 C! Thu Nov 08 2001 at 4:20:45

Perl variable containing the full string matched by the last successful regular expression pattern match. perldoc mnemonic: "like & in some editors." Read-only and dynamically scoped to the current block, i.e. when a block is closed, any $& set by a match inside that block disappears. Unfortunately, in Perl 5, using $& slows down all regex matches considerably; this includes any matches done by the program, including in other packages. This variable can also be called $MATCH if you use English. Related variables: $` (aka $PREMATCH) and $' (aka $POSTMATCH).

Usage example:

# $& is currently undef
$_ = 'hello, world';
/hello/;                 # $& is now 'hello'
/,...rld/;               # $& is now ', world'
/camel/;                 # $& is still ', world' -- match
                         #    unsuccessful
{
                         # $& is still ', world' -- no
                         #    match carried out yet in
                         #    innermost block
    /^he/;               # $& is 'he'
    /^h(?=ello)/;        # $& is 'h' -- lookahead is
                         #    zero width
}                        # $& reverts to ', world'
                         #    (previous value) when block
                         #    is closed
Y'know, if you log in, you can write something here, or contact authors directly on the site. Create a New User if you don't already have an account.