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?