in reply to Match operator giving unexpected output
Hello ysreenu, and welcome to the Monastery!
First, when scalar is applied to an array, it returns the number of elements in the array. But when scalar is applied to a list, it returns the last element in that list:
16:12 >perl -wE "say scalar('a', 'e', 'i', 'o', 'u');" Useless use of a constant ("a") in void context at -e line 1. Useless use of a constant ("e") in void context at -e line 1. Useless use of a constant ("i") in void context at -e line 1. Useless use of a constant ("o") in void context at -e line 1. u 16:13 >
Second, calling m/.../g in scalar context finds one match only, and advances the pointer to the next position in the string following the last match. So your two calls in Phase-2 eat up the first two occurrences of “ink” in the string. Then in Phase-3, since the pointer has not been reset, the call to m/.../g in list context finds only the remaining matches, which is why you get 4 and not 6.
Update: See “Global matching” in Using regular expressions in Perl.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Match operator giving unexpected output
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 Anonymous Monk on Jan 13, 2015 at 23:32 UTC | |
| |
|
Re^2: Match operator giving unexpected output
by ysreenu (Initiate) on Jan 13, 2015 at 09:28 UTC |