ysreenu has asked for the wisdom of the Perl Monks concerning the following question:
#!/usr/bin/perl -wl use strict; use warnings; =head This is perl 5, version 14, subversion 2 (v5.14.2) built for i686-linu +x-gnu-thread-multi-64int (with 57 registered patches, see perl -V for more detail) =cut my $string = "blink mink chink sink wink dink nn kkkk"; print "Phase-1:"; my @cnt_arr = $string =~ /ink/g; print "count array = @cnt_arr"; print "substring is found ", scalar(@cnt_arr), " times"; #prints 6 print "\nPhase-2:"; #attempts to do the same without the use of @cnt_arr print "substring is found ", scalar($string =~ /ink/g), " times"; #prints only 1 print "after 1, string = $string"; print "substring is found ", scalar(($string =~ /ink/g)), " times"; #an attempt to convert to array context, but still prints 1 print "after 2, string = $string"; print "\nPhase-3:"; @cnt_arr = $string =~ /ink/g; print "count array = @cnt_arr"; print "substring is found ", scalar(@cnt_arr), " times"; #now prints 4 !! print "after 3, string = $string"; # $string content remains the same throughout but match operator #is giving different results in phase-1 and phase-3
Phase-1:
count array = ink ink ink ink ink ink
substring is found 6 times
Phase-2:
substring is found 1 times
after 1, string = blink mink chink sink wink dink nn kkkk
substring is found 1 times
after 2, string = blink mink chink sink wink dink nn kkkk
Phase-3:
count array = ink ink ink ink
substring is found 4 times
after 3, string = blink mink chink sink wink dink nn kkkk
The output of match operator in phase-3 is showing only 4
substring matches even though the content of variable
$string remains the same.
Can you please explain why this is happening and how to
overcome it so that the number of substring matches is
consistent in phase-1 and phase-3.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Match operator giving unexpected output
by Athanasius (Archbishop) on Jan 13, 2015 at 06:18 UTC | |
by LanX (Saint) on Jan 13, 2015 at 11:22 UTC | |
by Anonymous Monk on Jan 13, 2015 at 11:53 UTC | |
by LanX (Saint) on Jan 13, 2015 at 12:02 UTC | |
by Anonymous Monk on Jan 13, 2015 at 23:29 UTC | |
| |
by ysreenu (Initiate) on Jan 13, 2015 at 09:28 UTC | |
|
Re: Match operator giving unexpected output (source)
by Anonymous Monk on Jan 13, 2015 at 08:27 UTC | |
by ysreenu (Initiate) on Jan 13, 2015 at 09:53 UTC |