I want to do this in Perl:
>> "foo bar baz".scan /(\w+)/
=> [["foo"], ["bar"], ["baz"]]
Any suggestions?
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 ).
Also, split, e.g.,
my $x = "foo bar baz";
my @elem = split(' ', $x);
OR
my @elem = split(/\w+/, $x);
etc.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With