How can I print the values of an array. I have tried several ways but I am unable to get the required values out of the arrays:
@array; Dumper output is as below :
$VAR1 = [
'a',
'b',
'c'
];
$VAR1 = [
'd',
'e',
'f'
];
$VAR1 = [
'g',
'h',
'i'
];
$VAR1 = [
'j',
'k',
'l'
];
for my $value (@array) {
my $ip = $value->[0];
DEBUG("DEBUG '$ip\n'");
}
I am getting output as below, which means foreach instance I am only getting the first value.
a
d
g
j
I have tried several approaches :
First option :
my $size = @array;
for ($n=0; $n < $size; $n++) {
my $value=$array[$n];
DEBUG( "DEBUG: Element is as $value" );
}
Second Option :
for my $value (@array) {
my $ip = $value->[$_];
DEBUG("DEBUG Element is '$ip\n'");
}
What is the best way to do this?
my $ip = join "", @$value;my $ip = $value->[0];dereferences the value from the first[0]index position of each array. You want to dereference (and loop over) each of the anonymous arrays inside your "outer" array (in this case@array). Your "First option" is closer (you're trying to loop) but you are looping over the "$size" of the outer array instead of each inner anonymous array. Your second option is a shorter way of making the same mistake :-) It is a common error: loops and dereferencing are different - but they often happen at the same time!$valueis an array (referenced by that scalar) which is why the sigil looks like:@$. If you usePerl::Criticon your code with the--crueloption you'll find that that@{ $value }is the preferred (i.e. Perl Best Practices) syntax. :-)