On 2002.05.18, Tim Hammerquist <tim / vegeta.ath.cx> wrote: > Dossy graced us by uttering: > > Maybe this is Perl envy, maybe I'm just doing something wrong. > > I'd like to be able to say this: > > > > x, y = "foo bar" =~ /(foo) (bar)/ > > > > and x == "foo" and y == "bar" > > The main problem I see with this (even as a perl idiom) is that you're > attempting to assign variables without checking the success of the > match. Without knowing the actual code you'll be using this example > with, it's a valid warning that, if the regex doesn't match the string, > then x would be assigned the result of the match (nil) and y would > retain the value it held before the statement (possibly nil as well). > > A more perlish idiom would be: > > if ("foo bar" =~ /(foo) (bar)/) { > ($x, $y) = ($1, $2); > } No, the Perlish idiom is: ($x, $y) = ("foo bar" =~ /(foo) (bar)/); As I said, this is more Perl wantarray() envy. In perl, the =~ operator knows if it's being used in the context of expecting a scalar vs. an array. If it's a scalar context, it returns 1 if there was a match or 0 if there wasn't. In an array context, it returns $1..$n match expressions as an array. > which translates to: > > if /(foo) (bar)/ =~ "foo bar" > x, y = $1, $2 > end > > or > > if /(foo) (bar)/ =~ "foo bar" > x, y = $~[1..2] > end Sigh. ;-) I guess it'll have to do. ;-) -- Dossy -- Dossy Shiobara mail: dossy / panoptic.com Panoptic Computer Network web: http://www.panoptic.com/ "He realized the fastest way to change is to laugh at your own folly -- then you can let go and quickly move on." (p. 70)