Click to See Complete Forum and Search --> : [RESOLVED] shift doesn't work with multidimensional lists


Ultimater
10-10-2005, 09:05 AM
problem:
shift doesn't seem to work with multidimensional lists.

my @twodArray=(['one','two'],['three','four']):
print shift @twoArray;#causes an error


situation:
I'm in search of a shift method that wouldn't be picky about non-scalar values:

my @twodArray=(['one','two'],['three','four']):
print mshift @twoArray;#one
print mshift @twoArray;#two
print mshift @twoArray;#three
print mshift @twoArray;#four

Any ideas how to define such a method?

Thanks in advance

fireartist
10-10-2005, 11:25 AM
my @twodArray=(['one','two'],['three','four']):
print shift @twoArray;#causes an error


If you'd used strict + warnings, you would have discovered that's broken.
The first line should end with a ; instead of :
And you misspelt the variable name on the second line.


use strict;
use warnings;

my @twodArray = (['one','two'],['three','four']);

print shift @twodArray;


This gives the output

ARRAY(0x3e57f8)
$VAR1 = [
'three',
'four'
];

The ouput shows that when you try printing a reference
( ['one', 'two] is an array reference )
you only get a memory address - pretty much useless


my @twodArray=(['one','two'],['three','four']):
print mshift @twoArray;#one
print mshift @twoArray;#two
print mshift @twoArray;#three
print mshift @twoArray;#four


Your mistaken here, @twodArray only contains 2 elements.
The first is an array reference containing ['one', 'two']
the second is an array reference containing ['three', 'four']

Remember, it's 2 dimensional:


use strict;
use warnings;
use Data::Dumper;

my @twodArray = (['one','two'],['three','four']);

for my $arrayref (@twodArray) {

print Dumper $arrayref; #peek at it's contents

local $\ = "\n";

print shift @$arrayref;
print shift @$arrayref;
}


outputs:


$VAR1 = [
'one',
'two'
];
one
two
$VAR1 = [
'three',
'four'
];
three
four



Notice that to be able to use shift, you must dereference the array-ref into an array, that's what the @$arrayref is for.

To access the individual elements:

use strict;
use warnings;

my @twodArray = (['one','two'],['three','four']);

for my $arrayref (@twodArray) {
local $\ = "\n";

print $arrayref->[0];
print $arrayref->[1];
}

Ultimater
10-10-2005, 11:38 AM
Thanks a lot for the reply fireartist! I would have never thought of $arrayref->[0] nor shift @$arrayref!

fireartist
10-10-2005, 04:22 PM
it's all in the perl reference docs (http://perldoc.perl.org/perlref.html), or

perldoc perlref