in reply to Help needed in populating the hash
Let's take that code, add strictures then make it a little more Perlish. First for strictures:
use strict; use warnings; use Data::Dumper; for ($i=0;$i<5;$i++) { $x{$i}="x"; } print Dumper($x);
which gives us a great crop of errors:
Global symbol "$i" requires explicit package name at noname.pl line 5. Global symbol "$i" requires explicit package name at noname.pl line 5. Global symbol "$i" requires explicit package name at noname.pl line 5. Global symbol "%x" requires explicit package name at noname.pl line 6. Global symbol "$i" requires explicit package name at noname.pl line 6. Global symbol "$x" requires explicit package name at noname.pl line 10 +. Execution of noname.pl aborted due to compilation errors.
Note that we have a bunch of errors grumbling about $i, one for %x and one for $x. Previous answers have addressed the %x/$x issue so let's fix the errors by declaring the variables we actually want and adopt roboticus's fix for the bogus $x:
use strict; use warnings; use Data::Dumper; my %x; for (my $i = 0; $i < 5; $i++) { $x{$i} = "x"; } print Dumper (\%x);
Now let's look at a few more Perlish versions of that code:
#1/ Perl for loop: my %x; for my $i (0 .. 4) { $x{$i} = "x"; } #2/ For as a statement modifier $x{$_} = 'x' for 0 .. 4; #3/ map generating hash key/value pairs: %x = map {$_ => 'x'} 0 .. 4; #4/ hash slice and x operator: @x{0 .. 4} = ('x') x 5;
These are (arguably) ranked in order of Perl experience required to understand them. As a beginner I'd highly recommend the Perl for loop. It's way better than the C for loop for a variety of reasons. The other versions are there as a teaser to show why Perl is known for TIMTOWTDI. They each have their place and illustrate important Perl constructs, but probably oughtn't be the first tool of choice until you fully understand what is going on with them.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Help needed in populating the hash
by anneli (Pilgrim) on Oct 16, 2011 at 04:02 UTC | |
by asab (Sexton) on Oct 16, 2011 at 12:38 UTC |