in reply to Syntax Perl Version support $c = () = $a =~ /\./g
my $c = () = $a =~ /\./g;
This statement evaluates a regex in list context (imposed by the empty parens):
() = $a =~ /\./g
and then evaluates the contents of the intermediate list captured by the parens in scalar context (imposed by the scalar assignment):
my $c = ()
which evaluates to the number of elements in the list.
Some variants of this syntax (in which the regex matches are captured instead of being thrown away):
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "print 'perl version: ', $]; ;; my $s = '3.5.9'; ;; my @ra; my $c = @ra = $s =~ m{ \d }xmsg; dd $c, \@ra; ;; $s = '8.6.5.1'; ;; $c = my @rb = $s =~ m{ \d }xmsg; dd $c, \@rb; " perl version: 5.008009 (3, [3, 5, 9]) (4, [8, 6, 5, 1])
... when did Perl begin supporting this type of structure?
AFAIK, Perl 5.x has always supported this, and I believe 4.x did as well, but I'm too lazy to do the research. (Update: See this for pertinent info on Perl 5 support for the =()= "operator," and this for Perl 4 support (none).) This is a well-known and safe Perl idiom. In general, look for discussions of "context" and "context dependence."
Update: See also Context tutorial in the Tutorials section of the Monastery.
Give a man a fish: <%-{-{-{-<
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Syntax Perl Version support $c = () = $a =~ /\./g
by haukex (Archbishop) on Jul 17, 2018 at 19:13 UTC | |
by h2 (Beadle) on Jul 17, 2018 at 19:16 UTC | |
Re^2: Syntax Perl Version support $c = () = $a =~ /\./g
by shmem (Chancellor) on Jul 17, 2018 at 22:47 UTC | |
Re: thanks all
by h2 (Beadle) on Jul 17, 2018 at 19:14 UTC |