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:
Jenda Krynicky
Date:
February 6, 2002 14:34
Subject:
Re: Accessing previous element of an array in a 'foreach' loop
Message ID:
3C61BDAF.12783.C51E178@localhost
From:           	Jeff 'japhy' Pinyan <jeffp@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.

So let's store a reference ;-) Then we will not need the $is_first_iter 
variable :

	#!perl
	my @a = qw(a b c);
	my $last;
	foreach (@a) {
		$$last = 'XXX' if ($_ eq 'c' and defined $last);
		# ...
		$last = \$_;
	}

	print join(', ',@a);
	__END__


Jenda

=========== Jenda@Krynicky.cz == http://Jenda.Krynicky.cz ==========
There is a reason for living. There must be. I've seen it somewhere.
It's just that in the mess on my table ... and in my brain.
I can't find it.
					--- me

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