Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Perl equivalent for String.scan found in Ruby?

Tags:

regex

perl

I want to do this in Perl:

>> "foo bar baz".scan /(\w+)/
=> [["foo"], ["bar"], ["baz"]]

Any suggestions?

like image 356
klochner Avatar asked Aug 08 '09 00:08

klochner


3 Answers

This does essentially the same thing.

my @elem = "foo bar baz" =~ /(\w+)/g

You can also set the "default scalar" variable $_.

$_ = "foo bar baz";
my @elem = /(\w+)/g;

See perldoc perlre for more information.


If you only want to use that string as an array, you could use qw().

my @elem = qw"foo bar baz";

See perldoc perlop ​ ​( Quote and Quote-like Operators ).

like image 64
Brad Gilbert Avatar answered Sep 19 '22 13:09

Brad Gilbert


Also, split, e.g.,

my $x = "foo bar baz";
my @elem = split(' ', $x);

OR

my @elem = split(/\w+/, $x);

etc.

like image 36
Chris Cleeland Avatar answered Sep 19 '22 13:09

Chris Cleeland


They key perl concept is scalar vs list context. Assigning an expression to an array forces list context, as does something like a while loop.

Thus, the equivalent of the block form of String#scan is to use the regexp with a while loop:

while ("foo bar baz" =~ /(\w+)/) {
    my $word = $1;
    do_something_with($word);
}
like image 42
robc Avatar answered Sep 21 '22 13:09

robc