James, I hope this is my last question. I appreciate your (and everyone else's that has contributed) generousity.
Not a problem. Hope I'm helping more than I'm confusing.
Why does "@$y[$i]" work here, and "foreach $i (keys %$x)" works to fetch the keys from a reference to a hash, but I use $$x{$i} to fetch hash reference element values instead of %$x{$i}?
This seems very inconsistent to me.
Which is exactly why it's not the preferred way of getting things done and triggers a warning, if they're active. Aren't warnings nice? Won't ever have to worry about you writing 3,000 lines of Perl without warnings, will I? <wink>
Just like you use $$x{$i} to fetch from a hash reference, use $$y[$i] to fetch from an array reference. It's easy to remember to. If you want a scalar as the end result, it starts with a $. If you want the whole array or whole hash instead, use @ or %.
sub print_array { my ($y, $n) = @_; for my $i ( 0 .. $#$y ) { print "print_array using .. y[$i] = @$y[$i]\n";
Simple change, as I explained above:
print "print_array using .. y[$i] = $$y[$i]\n";
} } # It was not my idea to use undeclared variables! # Are we creating a reference to a hash here? $undeclared[0] = 'a'; $undeclared[2] = 'b'; $undeclared[3] = 'c'; &print_array([EMAIL PROTECTED], 3);
No @undeclared is an array, not a hash. This stores a, b and c in non-consecutive (index 1 is missing) positions in that array, then calls print_array with a reference to the array and the number of elements. Which isn't being used in print_array at all, so why bother? You can always get the number of elements with the array, so avoid using these 'magic numbers'.
Here are some other possible print_arrays:
# keeping the reference, called with print_array([EMAIL PROTECTED]) sub print_array { my $array_ref = $_[0]; print "print_array $_\n" foreach (@$array_ref); }
Some changes here. I rewrote the foreach loop to use the default $_. Also note that I dereference the array inside the loop and forget about it. This way I don't even need an index number, I'm just walking the list of elements. We can even drop that last variable:
sub print_array { print "print_array $_\n" foreach (@{ $_[0] }); }
The braces are required in that dereference though. Now, if we want to ditch the references altogether (and I sure can't see why we're using them), we could go to the simple:
# losing the reference, called with print_array(@array) sub print_array { print "print_array $_\n" foreach (@_); }
I don't know about you, but I think that's getting a lot easier to follow. Use what you know though. "There's more than one way to do it."
Good luck.
James
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]