Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Evaluating Multidimensional Arrays and References

by mr_dont (Beadle)
on Aug 10, 2001 at 19:41 UTC ( [id://103915]=perlquestion: print w/replies, xml ) Need Help??

mr_dont has asked for the wisdom of the Perl Monks concerning the following question:

Hi PerlMonks!

Last night I was writing a script and I was stumped by its behaviour... Basically, it contains a data object which is a hash containing a multidimensional array (a 2n one)...

So I might have data like this: @{$self->{_mydata}[2][3]} = "John";

In one of my methods, when I print this out, it gives my the correct answer:

print "My name is @{$self->{_mydata}[2][3]}\n";
Output: My name is John

However, when I try to evaluate it, It doesn't work:

if ((@{$self->{_mydata}[2][3]}) eq "John") { print "My name is @{$self->{_mydata}[2][3]}\n"; }

The above code won't print anything... Why isn't this working? Anyone know what I am doing wrong?
Thanks Fellow Monks..!

Replies are listed 'Best First'.
Re: Evaluating Multidimensional Arrays and References
by c-era (Curate) on Aug 10, 2001 at 19:46 UTC
    You are evaluating it in array context, try:
    if ($self->{_mydata}[2][3] eq "John") or if ($$self{_mydata}[2][3] eq "John")
    and your print statment should be:
    print $self->{_mydata}[2][3]; or print $$self{_mydata}[2][3];
Re: Evaluating Multidimensional Arrays and References
by bikeNomad (Priest) on Aug 10, 2001 at 19:48 UTC
    The problem is that the @{...} returns an array. When you compare this with "John", it gets converted into a scalar, which is the size of the array (probably 1 in this case). So you're saying 'if 1 eq "John"'...

    The reason that it prints is that its contents are being interpolated into the string (separated by $, but that doesn't matter if you have one element).

    What you probably want is to say:

    if ($self->{_mydata}[2][3][0] eq "John") { print "My name is $self->{_mydata}[2][3][0]\n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://103915]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2024-04-25 21:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found