
rpaskudniak
User

Jul 7, 2010, 8:50 PM
Post #3 of 5
(669 views)
|
|
Re: [rpaskudniak] Access elements and Length of an array when I have only the reference
[In reply to]
|
Can't Post
|
|
Thanks, Bill. Your solution was real close but it took some experimentation to get it quite right. While the perldoc didn't quite address this, I managed to glean something from it and your code. Here's the code that worked; note that I have removed some of the parentheses you had used.
#!/usr/bin/perl -w #-d # # testglob.pl # use strict; use diagnostics; my @one_list = (1, 2, 3, 4); print "Whole list before call: @one_list\n"; append_one(\@one_list); print "Whole list after call: @one_list\n"; sub append_one { my $list_ref = shift (@_); #printf("Before push: Top entry in array is %d\n", $#($list_ref)); for (my $lc = 0; defined($list_ref->[$lc]); $lc++) { printf("Entry[%d]=%d\n", $lc, $list_ref->[$lc]); } print "Pushing one more value on the array\n"; push (@$list_ref, 5); #printf("After push: Top entry in array is %d\n", $#($list_ref)); for (my $lc = 0; defined($list_ref->[$lc]); $lc++) { printf("Entry[%d]=%d\n", $lc, $list_ref->[$lc]); } } This produced:
Jake@Maxwell ~/scripts$ ./testglob.pl Whole list before call: 1 2 3 4 Entry[0]=1 Entry[1]=2 Entry[2]=3 Entry[3]=4 Pushing one more value on the array Entry[0]=1 Entry[1]=2 Entry[2]=3 Entry[3]=4 Entry[4]=5 Whole list after call: 1 2 3 4 5 OK, this was a great start. However, the first part of my question remains unanswered. You can see the commented printfs in append_one(), where I am trying to obtain the equivalent of $#array from the array reference. I have tried many permutations of $, #, {}, () and all earn me a syntax error. Short of forcing the caller to explicitly pass $#array to the subroutine, how can I access the $# of the array, given only the reference? I used the "defined()" operator here just to get by, but that is a rigged test. I already described why I don't want to rely on this as a loop terminator in general. This is getting to be FUN! Thanks much! -------------------- -- Rasputin Paskudniak (In perpetual pursuit of undomesticated, semi-aquatic avians)
|