Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Easy way to pass in previous array element?

Status
Not open for further replies.

StormMedic85

Programmer
Sep 7, 2007
20
US
Within a subroutine, I need to pass in two parameters...a current value (which will be passed in from the value array), and the previous value (the element in the value array BEFORE the current element). I need it to do this for every function call. Any suggestions? The array length varies each time the program is ran so I can't simply use @value[x], where x is the element number.

Thanks very much for any help!
 
Something like

@array = qw(this is a test);
print $array[$#array],' ',$array[$#array-1],"\n";

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
Thanks! That's extremely helpful and exactly what I want! I'm just having difficulties in incorporating it into my for loop...

for ($i=0; $i<$size; $i++){
$thickness = &layer($altitude[$i],$altitude[$#altitude-1]);
}

I can't do $altitude[$i][$#altitude[$i-1] or I get a syntax error. :-\

Any ideas? Thanks so much!

 
Your code makes it look like you are passing all of the array elements to &layer() two at a time. Is that true? If so:

Code:
for my $i (1..$#altitude){
   $thickness = &layer($altitude[$i],$altitude[$i-1]);
}

but unless you are doing something with $thickness it will always equal the value returned by the last iteration of the loop.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Minor simplification:

Code:
[olive][b]for[/b][/olive] [url=http://perldoc.perl.org/functions/my.html][black][b]my[/b][/black][/url] [blue]$i[/blue] [red]([/red][fuchsia]1..[/fuchsia][blue]$#altitude[/blue][red])[/red][red]{[/red]
	[blue]$thickness[/blue] = [maroon]layer[/maroon][red]([/red][blue]@altitude[/blue][red][[/red][blue]$i[/blue],[blue]$i[/blue]-[fuchsia]1[/fuchsia][red]][/red][red])[/red][red];[/red]
[red]}[/red]

- Miller
 
At a glance it looks like you'll miss out on the first data point, but you won't have a previous reference point, is this what you want?

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top