I am starting to learn Perl and this is just a basic little for loop for which I get a strange output and was hoping for some clarity on this.
@numbers = {1,4,5,6,7,8,9};
for(my$i = 0; $i<=$#numbers; $i++)
{
print ("$numbers[$i}\n");
}
the output is HASH(0x23a09c).
What does this actually mean and why do I get this result.
regards
Arian
You want this:
With
{1,4,5,6,7,8,9}you’re actually creating a reference to an anonymous hash containing the key value pairs(1 => 4, 5 => 6, 7 => 8, 9 => undef). When you write@numbers = {1,4,5,6,7,8,9};that reference becomes the sole scalar stored in the@numbersarray.Furthermore, if you just want to iterate over the elements, no need to use the “classic” style with a counter.
You can do:
Make sure you have
use strict;anduse warnings;at the beginning of every Perl script you write. Those directives enableperlto catch errors and warn about certain possibly erroneous code. As a beginner, you might want to couple those withwarningswith diagnostics to get more detailed information.These are very handy, especially when starting out with Perl as they help you prevent shooting yourself in the foot.