Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Regex question

by betterworld (Curate)
on Oct 14, 2008 at 09:48 UTC ( [id://716930]=note: print w/replies, xml ) Need Help??


in reply to Regex question

This will work:

my ($number) = $data =~ /\d+/g;

The match operator returns the matched substrings only in list context, which is why your first code worked (assignment to an array). By using extra parentheses (like in my code above), you can turn a scalar assignment into a list assignment.

Update: You won't need the /g flag if you use capturing parentheses:

my ($number) = $data =~ /(\d+)/;

Replies are listed 'Best First'.
Re^2: Regex question
by chromatic (Archbishop) on Oct 14, 2008 at 18:22 UTC
    (assignment to an array)

    I think you mean assignment to a list.

      Hmm, I meant this line of the OP's code:

      my @nums = $data =~ /\d+/g;

      I think it can be called an assignment to an array, which imposes a list context on the right-hand side, as it is described in perldata:

      Assignment to a scalar evaluates the right-hand side in scalar context, while assignment to an array or hash evaluates the righthand side in list context. Assignment to a list (or slice, which is just a list anyway) also evaluates the righthand side in list context.

      I think this would be an assignment to a list:

      my ($num) = ...
Re^2: Regex question
by JavaFan (Canon) on Oct 14, 2008 at 10:41 UTC
    Yeah, but it's actually the other way around. If you're using /g in list context, and only want to capture the entire match, you don't need the parenthesis. That is, if you have any capturing parenthesis, no additional parenthesis are implied.
      If you're using /g in list context, and only want to capture the entire match, you don't need the parenthesis.

      I don't think that this contradicts what I wrote.

      I was only suggesting to use parentheses rather than /g, because I wouldn't use the /g flag unless I really want to match several occurrences.

      (However, as Larry Wall put it: The argument against using an operator for other than its primary purpose strikes me the same as the old argument that you shouldn't have sex for other than procreational purposes. Sometimes side effects are more enjoyable than the originally intended effect.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://716930]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-03-19 05:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found