CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Intermediate: Access elements and Length of an array when I have only the reference: Edit Log


Jul 6, 2010, 4:10 PM

Views: 1465
Access elements and Length of an array when I have only the reference


At the risk of reinventing the wheel -the CPAN module Text::ParseWords - (Thanks, BillKSmith), I would like to know how to do this: I want to pass an array reference to a subroutine and:
- Determine the number of items in the array
- Get a value from inside that array e.g. $my_array[3]
- Diddle the array e.g shift, push, change a value. The code I would like to run would look something like:

my @one_list = (1, 2, 3, 4); 
print "@one_list\n";
append_one(\@one_list); # Notice: Passing array reference
print "@one_list\n";

sub append_one
my @my_list = @_; #This is definitely messed up code

printf("Before push: Top entry in array is %d\n", $#my_list);
push (@my_list, 5);
printf("After push: Top entry in array is %d\n", $#my_list);

Y'all know, of course, that the code presented above will NOT work as desired; in the subroutine, @my_list is an array of one entry - the array reference that was passed. Pushing the five only appends the 5 to that tiny array, leaving the original array untouched. (The Before and After values are 0 and 1.) I am guessing at *-dereferencing of a scalar and using that in an array context but I would need a syntax for that.

How can I accomplish my nefarious designs?Angelic

Note: Even if I already knew how to access the values in the array, I would not scan up until an entry is undefined. In Perl, an array might have many entries undefined before the last one.

Thanks much!
-- Rasputin Paskudniak (In perpetual pursuit of undomesticated, semi-aquatic avians)

(This post was edited by rpaskudniak on Jul 6, 2010, 4:13 PM)

Edit Log:
Post edited by rpaskudniak (User) on Jul 6, 2010, 4:13 PM: Clarify the subject line

Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives