On Dec 6, Paul Johnson said:

>On Fri, Dec 06, 2002 at 11:58:37AM -0500, Danny Miller wrote:
>
>> Strictly speaking, ++$count is faster than $count++.
>
>Strictly speaking, perl will convert $count++ to ++$count if it can.

Strictly speaking, there is another major difference no one has mentioned
yet (and that many people might have trouble understanding).  Using
$count++ returns a NUMBER OR STRING, and then increments $count's value.
++$count increments $count's value, and returns THE SCALAR ITSELF.

How does this matter?  Well, watch:

  $i = 2;
  $j = ++$i / ++$i;

What do you think $j will be?  3/4?  Nope.  4/4, or 1.  The reason is
because the ++$i form is a "footnote" type of thing.  Basically it means
"increment $i, but leave $i here" whereas $i++ means "return $i's value,
and then increment it".

Want to have your mind hurt?

  $i = 2;
  @j = (++$i, ++$i, ++$i);

What do you think @j will be?  (5,5,5)?  Yes, it will.  The elements of
the list ARE $i themselves, and each element's expression increments $i
once; so $i becomes 5, and then the list is ($i, $i, $i), and all those
are 5.  (Contrast this with ($i++, $i++, $i++), where the list is (2,3,4),
NOT ($i,$i,$i).)

Here's the brain-hurting:

  $i = 2;
  $j = ++$i + ++$i + ++$i;

What do you think $j will be?  3 + 4 + 5 = 12?  No.  5 + 5 + 5 = 15?  No.
(NO!?)  It will be 13.  4 + 4 + 5.  HOW does Perl manage that?  It's
because ++$i isn't executed until it's reached, and the THIRD one isn't
reached until the first two have been evaluated:

  $j = (++$i + ++$i) + ++$i;
  # ++$i sets $i to 3
  # ++$i sets $i to 4
  # ($i + $i) returns 8
  # ++$i sets $i to 5
  # 8 + $i returns 15

CRAZY.  Or logical.  Both, really.

Oops.  This is [EMAIL PROTECTED]  Sorry. ;)

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to