develooper Front page | perl.beginners | Postings from February 2002

Re: Accessing previous element of an array in a 'foreach' loop

Thread Previous | Thread Next
From:
Jeff 'japhy' Pinyan
Date:
February 6, 2002 14:01
Subject:
Re: Accessing previous element of an array in a 'foreach' loop
Message ID:
Pine.GSO.4.21.0202061659500.612-100000@crusoe.crusoe.net
On Feb 6, Brett W. McCoy said:

>On Wed, 6 Feb 2002, Carl Rogers wrote:
>
>> foreach(@array) {
>>
>> 	if ($_ =~/somecondition/) {
>> 	# I want to do something to the element prior to $_ ($_ - 1)
>> 	}
>> }
>
>The problem here is that $_ is a *copy* of the element in the array --
>modifying it does not modify the array (I think in earlier versions it was
>actually an alias, which, I have read, led to all sorts of abuse), so
>without some kind of a counter, you will not have any knowledge of the
>previous value.

Err, no.  $_ is STILL an alias.

  my @words = qw( once upon a time );
  length > 1 and $_ = ucfirst($_) for @words;
  print "@words";  # Once Upon a Time

The problem will be storing the PREVIOUS element, which WILL be a copy,
NOT an alias.

-- 
Jeff "japhy" Pinyan      japhy@pobox.com      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About