[prog] quick perl question

Jacinta Richardson jarich at perltraining.com.au
Thu Mar 4 18:50:37 EST 2004


> Anyone know if there's a way of checking what position in the array you're
> in during a perl foreach loop, without declaring some kinda count
> variable? Just sounded like the kind of thing there might be a bit of perl
> magic for...

Yup I know.

There isn't a way.

It's been brought up several times and always the answer has been:
	If you really need to do that, use a for loop
because the overhead of keeping that variable would be wasted 99.9% of the
time.

If you've never used for loops they tend to look like this:

	for(my $i = 0; $i < @array; $i++) {
		my $element = $array[$i];
		.....
	}

Remember that changing $array[$i] of course changes it _in_place_.  That
should be obvious.  Changing $element in my example above is only changing
a copy (references aside).

Note, however that a similar thing happens in foreach loops:

	foreach my $foo (@array) {
		$foo++;
	}

This increments each value in @array.  Note that ++ is a bit funny so
	$foo = 'a';
	$foo++;
is not the same as:
	$foo = 'a';
	$foo = $foo + 1;

The latter numifies 'a' which becomes zero, and then adds 1, resulting in
1.  The former does some magic and $foo becomes 'b'.  :)  'zz' becomes
'aaa' if you increment it.  :)   Great huh?

Php has a similar inconsistency.
	$a = 1.5;
	$a--;
What's $a?  It certainly isn't 0.5.

Increment and decrement operators should be used with care.   And I've
wandered so far off topic that I think I'll finish here.

	Jacinta
--
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +613 9354 6001         |  
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
(il),-''  (li),'  ((!.-'              |   www.perltraining.com.au   |



More information about the Programming mailing list