Nitesh
Nitesh

Reputation: 157

How to dereferrence the array

I am trying to retreive the the individual elements of the array stored as a reference.

my @list = ("three 13  3  1  91 3", "one   11  5  1  45 1",
            "two   12  7  1  33 2", "four  14  1  1  26 4");

my @refList = map { [$_, (split)[-1]] } @list;

# see what it is in @refList
use Data::Dumper;
print Dumper(@refList);

print "\n the value is $refList[0][0][1]";

Output

$VAR1 = [
          'three 13  3  1  91 3',
          '3'
        ];
$VAR2 = [
          'one   11  5  1  45 1',
          '1'
        ];
$VAR3 = [
          'two   12  7  1  33 2',
          '2'
        ];
$VAR4 = [
          'four  14  1  1  26 4',
          '4'
        ];

 the value is

But i need the output of

 print "\n the value is $refList[0][0][1]" as 13

How to get the value

Upvotes: 3

Views: 101

Answers (3)

Toto
Toto

Reputation: 91518

As refp said you're using too muck [0], you could do:

my @list    = ("three 13 3 1 91 3", "one 11 5 1 45 1", 
               "two 12 7 1 33 2", "four 14 1 1 26 4");

my @refList = map {[split]} @list;
print "\n the value is ", $refList[0][1];

But if you want to have these 3 levels, this will do the job:

my @list    = ("three 13 3 1 91 3", "one 11 5 1 45 1",
               "two 12 7 1 33 2", "four 14 1 1 26 4");
my @refList = ([map {[split]} @list]);
print "\n the value is ", $refList[0][0][1];

Upvotes: 3

Filip Roséen
Filip Roséen

Reputation: 63892

You are using one too many [0] in your print, to reference the value 3 you are talking about it should read

$refList[0][1]

I think I'm going mental, I swear I thought you were talking about the value 3 earlier. Though I see no changes in your post, odd.. I blame the lack of sleep.

If you are looking for the value 13 (which your posts currently says) you should change your code to something as the below

use Data::Dumper;

my @list    = ("three 13 3 1 91 3", "one 11 5 1 45 1", "two 12 7 1 33 2", "four 14 1 1 26 4");
my @refList = map {@_=split;$_[0]=$_;[@_]} @list;

# print Dumper [@refList];

print "\n the value is ", $refList[0][1];

If you just want each string to be turned into an array reference, use this as the declaration/definition of @refList.

my @refList = map {[split]} @list;

Upvotes: 6

Pradeep
Pradeep

Reputation: 3153

my @list = ( "three 13 3 1 91 3", "one 11 5 1 45 1", "two 12 7 1 33 2", "four 14 1 1 26 4" );

my @refList = map { my @t = split; shift(@t); [ $_, @t ]; } @list;

# see what it is in @refList
use Data::Dumper;
print Dumper(@refList);

print "\n the value is $refList[0][0][1]";

Upvotes: -1

Related Questions