2

I already know I can print all regex matches in one go (though without separators) like this:

perl -e '$t="10 hello 25 moo 31 foo"; print ( $t =~ /(\d+)/g ) ; print "\n";'
# 102531

I'm also aware I can get regex matches as named array, and then assign an individual match to a variable:

perl -e '$t="10 hello 25 moo 31 foo"; @n=( $t =~ /(\d+)/g ); $o=$n[1]; print "$o\n";'
# 25

I'm also aware I could do the regex, and then refer to, say, $1:

perl -e '$t="10 hello 25 moo 31 foo"; $t =~ /(\d+)/g ; $o=$1; print "$o\n";'
# 10

... although, for some reason, $2 doesn't work here - why?

What I would like to do, is assign a specific match from the regex to a variable in one go / a single line (without using the named array). Since the above tells us the results of the regex match are an array, I thought something like this idiom (used with dereferencing arrays?) would work:

$o = @{ ( $t =~ /(\d+)/g ) }[1];

but unfortunately it doesn't:

perl -e '$t="10 hello 25 moo 31 foo"; $o=@{ ( $t =~ /(\d+)/g ) }[1]; print "$o\n";'
#

So, is there a way to achieve such a single line assignment of a regex match array in Perl?

sdaau
  • 36,975
  • 46
  • 198
  • 278

2 Answers2

4

Just change this:

perl -e '$t="10 hello 25 moo 31 foo"; $o=@{ ( $t =~ /(\d+)/g ) }[1]; print "$o\n";'

to:

perl -e '$t="10 hello 25 moo 31 foo"; $o=( $t =~ /(\d+)/g )[1]; print "$o\n";'
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    Many thanks for that @M42 - can't believe how close I was to finding it, yet missed it `:)` Cheers! – sdaau Oct 18 '13 at 10:11
3

In addition to M42's method of using a subscript on a list, you can use direct assignment

my (undef, $x) = $t =~ /\d+/g;

I use undef as a placeholder here, but you can also use another variable. This method simply discards the first match. Basically, the scalars on the left hand side are assigned values from the right hand side in the order they appear. Like so:

my ($one, $two, $three) = (1, 2, 3, 4);

Here the assignment will result in: $one == 1, $two == 2 and $three == 3. 4 is discarded.

TLP
  • 66,756
  • 10
  • 92
  • 149