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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
dereference an array reference

 



newuser2014
New User

Apr 27, 2014, 8:24 AM

Post #1 of 3 (2524 views)
dereference an array reference Can't Post

Hi,

I have a very simple question here I don't understand. I have passed an array reference to a hash as one of elements of another array. When I tried to dereference the array reference, I have got nothing in it. All previous steps work until the last one. Is there something wrong with the following code? Thank you for helping me to understand Perl.

my @array = (1, 2);
my %hash;
my $key; ($key is some string)
my $hash{$key} = [$val1, \@array, $val2]; ($val1, $val2 are some strings)
my $tmpref = $hashref{$key};
my $tmparrayref = @$tmpref[1];
print "@$tmparrayref\n";


Rest of values can be retrieved but @$tmparrayref returns nothing.
Is my way of derefferencing wrong?
Thank you for responding.

Amy Z.


Laurent_R
Veteran / Moderator

Apr 27, 2014, 9:44 AM

Post #2 of 3 (2521 views)
Re: [newuser2014] dereference an array reference [In reply to] Can't Post

Hi,

it would be better if you supplied actually executable code, rather than pseudo-code with comments such as "($val1, $val2 are some strings) ".

Second point, you would probably have discovered your error if you had included the following pragmata at or near the top of your script:

Code
use strict; 
use warnings;


You would have found that this line:

Code
my $tmpref = $hashref{$key};

is wrong because you have never defined %hashref, but only %hash.
Correcting this, this is what I get:

Code
use strict; 
use warnings;
my %hash;
my @array = (1, 2);
my $key = "bar";
$hash{$key} = ["foo", \@array, "baz"];
my $tmpref = $hash{$key};
my $tmparrayref = @$tmpref[1];
print "@$tmparrayref\n"; # print "1 2"


It does print "1 2", which is presumably what you expect.


newuser2014
New User

Apr 28, 2014, 10:55 AM

Post #3 of 3 (2453 views)
Re: [Laurent_R] dereference an array reference [In reply to] Can't Post

Thank you Lauren for taking the time to help with my issue. Yes, the pseudo code has some problem, but the original code is too long. I actually found the problem is I accidentally reset the original array to empty before accessing it -- dumb error. You run the code in a smaller program has inspired me to do the same and found the problem eventually.

Thanks again.



Amy

 
 


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

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