Strategy of ++/-- operator in Lists in perl

S

sln

Below is a Perl code sample of using increment operator on variables in lists.
Below that is a C++ equivalent.

The strategies are different for pre/post-increment as far as the list block,
as are the outcomes.

Can anybody explain the logic in this? To me, they both look incorrect. C++
possibly a little more so.

-sln

--------------------------------

## some_lists.pl
use strict;
use warnings;

my ($p,@ar);

print "\n";
$p = 0;
printf ("%d %d %d %d %d %d \n", $p++, ++$p, $p++, ++$p, $p++, ++$p);
# +1 +1 +1 +1 +1 +1
# going this way ---> 0 2 4
# 6 6 6 <--- going this way
$p = 0;
printf ("%d %d %d %d %d %d \n", $p++, $p++, ++$p, ++$p, $p++, $p++);
# +1 +1 +1 +1 +1 +1
# going this way ---> 0 1 4 5 <--- going this way
# 6 6
$p = 0;
printf ("%d %d %d %d %d %d %d %d\n", $p++, $p++, ++$p, ++$p, $p++, $p++, ++$p, ++$p);
# +1 +1 +1 +1 +1 +1 +1 +1
# going this way ---> 0 1 4 5
# 8 8 8 8 <--- going this way
$p = 0;
printf ("%d %d %d %d %d\n", $p++, ++$p, $p++, $p++, ++$p);
# +1 +1 +1 +1 +1
# going this way ---> 0 2 3
# 5 5 <--- going this way
$p = 0;
@ar = ( $p++, $p++, ++$p, ++$p, $p++, $p++, ++$p, ++$p ); print "@ar\n";
# 0 1 4 5
# 8 8 8 8

print "\n";
$p = 0;
@ar = ( $p++, $p++, ++$p, $p*=$p, $p++, $p=0, ++$p, ++$p ); print "@ar\n";
$p = 0;
@ar = ( $p++, $p++, ++$p, $p*=$p, $p++, $p++, ++$p, ++$p ); print "@ar\n";


__END__


/** C Equivalent **/


int p = 0;
printf ("%d %d %d %d %d %d \n", p++, ++p, p++, ++p, p++, ++p);
// +1 +1 +1
// 3 2 1 <--- going this way
// going this way ---> 3 3 3

p = 0;
printf ("%d %d %d %d %d %d \n", p++, p++, ++p, ++p, p++, p++);
// +1 +1
// 2 2 0 0 <--- going this way
// going this way ---> 2 2

p = 0;
printf ("%d %d %d %d %d %d %d %d\n", p++, p++, ++p, ++p, p++, p++, ++p, ++p);
// +1 +1 +1 +1
// 4 4 2 2 <--- going this way
// going this way ---> 4 4 4 4

p = 0;
printf ("%d %d %d %d %d\n", p++, ++p, p++, p++, ++p);
// +1 +1
// 2 1 1 <--- going this way
// going this way ---> 2 2
//
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top