in reply to $| pre and post increment and deincrement behavior
grep has no relevance here.
$|-- and --$| toggle the current value.
$|++ and ++$| set the value to 1.
$|-- and $|++ return the old value.
--$| and ++$| return the new value.
Normally, $| is set to 0.
For example,
print('$|--: '); $|=0; for (1..10) { print($|--, ' '); } print("\n"); print('--$|: '); $|=0; for (1..10) { print(--$|, ' '); } print("\n"); print('$|++: '); $|=0; for (1..10) { print($|++, ' '); } print("\n"); print('++$|: '); $|=0; for (1..10) { print(++$|, ' '); } print("\n");
outputs
$|--: 0 1 0 1 0 1 0 1 0 1 --$|: 1 0 1 0 1 0 1 0 1 0 $|++: 0 1 1 1 1 1 1 1 1 1 ++$|: 1 1 1 1 1 1 1 1 1 1
Update: $toggle^=1 works just as well as --$|, but it's less obfuscated and has no side-effects:
$,=", "; $\="\n"; @list = qw( a b c d ); $| = 0; print grep --$|, @list; # a, c $t = 0; print grep $t^=1, @list; # a, c
Update: If you need every Nth term, try the following:
$,=", "; $\="\n"; @list = qw( a b c d e f ); $n = 3; $t = $n-1; print grep !($t=($t+1)%$n), @list; # a, d
|
|---|