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

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

Thread Previous | Thread Next
Jeff 'japhy' Pinyan
February 6, 2002 14:01
Re: Accessing previous element of an array in a 'foreach' loop
Message ID:
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
RPI Acacia brother #734
** 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 Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About