[Israel.pm] List of all contexts in Perl

Offer Kaye offer.kaye at gmail.com
Sun May 30 12:07:49 PDT 2010


On Sun, May 30, 2010 at 7:01 PM, Shmuel Fomberg wrote:
>
> isn't the match operator behaves differently in scalar, list and boolean
> context?
> @matchs = $str =~ m/xxxx/g;
> $match_count = $str =~ m/xxxx/g;
> while ($str =~ m/xxxx/g) { ... }
>
> - Shmuel

Nope, the last line is just scalar context. I checked it with:

C:\Users\Offer>perl -le "my $str = qq(xxx1 g xxx2 c xxx3 h xxx4);while
($str =~ m/(xxx.)/g) {print qq('$+' , '$_')"}
'xxx1' , ''
'xxx2' , ''
'xxx3' , ''
'xxx4' , ''

Vs.:

C:\Users\Offer>perl -le "my $str = qq(xxx1 g xxx2 c xxx3 h xxx4);while
(scalar($str =~ m/(xxx.)/g)) {print qq('$+' , '$_')"}
'xxx1' , ''
'xxx2' , ''
'xxx3' , ''
'xxx4' , ''

As you can see adding an explicit "scalar" didn't change anything.
Compare the above BTW to list context using foreach:

C:\Users\Offer>perl -le "my $str = qq(xxx1 g xxx2 c xxx3 h
xxx4);foreach ($str =~ m/(xxx.)/g) {print qq('$+' , '$_')"}
'xxx4' , 'xxx1'
'xxx4' , 'xxx2'
'xxx4' , 'xxx3'
'xxx4' , 'xxx4'

Regards,
-- 
Offer Kaye


More information about the Perl mailing list