Printing "Multi-Dimensional" Array in Perl

I am having a problem attempting to print an array that contains arrays. When printing the array @dev which contains the other arrays, I am only managing to print the first three as it is indicated by the #printing in-line comments. The commented line #print($dev[4][2]); works fine, as well as any of the other combination of numbers within the allowable range. For some reason the for loop does not work. Help!?

my @dev;
my @tf;
my @a;
my @t;
my @f;
my @ofv;
my @tfv;

@tf = ('123456787', '123456788', '123456789'); #printing
@a = (78, 65, 57); #printing
@t = (70, 55, 42); #printing
@f = (77, 64, 56);
@ofv = ('true', 'false', 'false');
@tfv = ('false', 'true', 'true');       

@dev = (
    [@tf],
    [@a],
    [@t],
    [@f],
    [@ofv],
    [@tfv],
);

#print($dev[4][2]);

for (my $i = 0; $i <= (scalar(@tf) - 1); $i++) {
    for (my $j = 0; $j <= (scalar(@dev) - 1); $j++) {
        print($dev[$i][$j]);
        print("\n");
    }
}

Thank you.

Upvotes: 0

Views: 1112

Answers (3)

red0ct
red0ct

Reputation: 5055

Perl can be quite compact. This snippet of code do the same thing for my arrays @arr1, @arr2 and @arr3:

@arr1 = (1..10);
@arr2 = ('a'..'j');
@arr3 = ('.') x 10;

@multid = \(@arr1, @arr2, @arr3);
print "@$_\n" for (@multid);

OUTPUT:

1 2 3 4 5 6 7 8 9 10
a b c d e f g h i j
. . . . . . . . . .

Also the [] copies an array and gives a reference to it (It's an anonymous array in memory, regardless of the array, a copy of which he is). If there is no need to such duplicate, it is better to use the backslash \ which instead gives a reference to existing array without coping. (like & operator in C, as tell us perldoc)

Upvotes: 3

Jay.Zhao
Jay.Zhao

Reputation: 491

If you just want to show the data of such complex data struct, the modules Data::Dumper or Smart::Comments may be good options.

use Data::Dumper;
print Dumper(\@dev);

or

use Smart::Comments;
### @dev

The output is much more perl-style and not that readable, but is quite convenient to show the struct of such complex data.

Upvotes: 3

MondayMonkey
MondayMonkey

Reputation: 84

Your outermost for loop is constrained by the length of t, which is 3. It will never print more than three arrays.

If I understand what you're trying to do, you need top swap @t and @dev. That will print all your values.

That won't, however, print any array that is longer than 3 (the length of dev).

For that, you need:

@dev = (
    [@tf], # Probably meant tf
    [@a],
    [@t],
    [@f],
    [@ofv],
    [@tfv],
);

#print($dev[4][2]);

for (my $i = 0; $i < @dev; $i++) {
    for (my $j = 0; $j < @{ $dev[$i] }; $j++) {
        print($dev[$i][$j]);
        print("\n");
    }
}

Upvotes: 1

Related Questions