I'm new to Perl, and am trying to match a string enclosed within
parentheses, storing said string in a variable. Simple enough I would
guess.
An example of the text to search would be: "hello(world)", with the
variable holding 'world' once done.
How far off am I with:
$text = "hello(world)";
$new = $text =~ m/\(*\)/;
Quite far offI am assuming!!
Close, but not quite. First problem: you are making a typical
newbie mistake--confusing regexp syntax with the filematching
or "globbing" syntax found in many shells (and, for that
matter, in Perl when you do filename globbing). "*" doesn't
mean "match any number of any character", it means "match
any number (including zero) of the preceding character."
so this matches zero to any number of left parens, followed
by one right paren. In the string "hello(world)" your regexp
will match ")". The rexexp character for "match any
character (except newline)" is the period (.). So the
expression you want for "match any number of any characters"
is ".*".
Second problem: m// doesn't return what it matched. Well,
it can, but not in a scalar context, and the methods by which
you can get it to return what's matched are not I think
the most useful for what you're trying to do here. m//
returns 1 if you got a match and "" if you didn't, which
is handy if you're using it to check a conditional, but
less so if you want to extract what was matched. There
are a variety of ways to get what was matched, but for
your case the best way is probably to use capturing
parentheses, particularly since you *don't* want the
whole match--you want to strip off the parentheses.
This will do the trick:
if ($text =~ m/\((.*)\)/) {
$new = $1;
}
else {
# it wasn't there!
}
After a successful match, the capturing parentheses
populate the number variables--the first capture
goes in $1, the second in $2 and so on. Note that
these variables *only* get changed if the match
was successful, which is why the code I gave
makes the assignment only on a successful match.
--
Christopher Mattern
"Which one you figure tracked us?"
"The ugly one, sir."
"...Could you be more specific?"