in reply to Style and Preference on Loops
If you're on a Unix/Linux/Mac, type perldoc perl into a terminal window, and see all the documentation you already have installed on your machine. ( I dunno how to view it on MSDos, but I'd try typing the same thing in a cmd shell. ) or you can go to CPAN or ask google to find 'perl pod'. perlsyn is the section which actually discusses syntax.
Briefly, there is almost never a reason to use the C style for loop. If you want to iterate over a list, let Perl handle the hard part:
for my $elem ( @$mysql ) { my $field1 = $elem->{field}; }
If you want to keep track of the index number, use the range operator, let Perl handle the hard part:
for my $idx ( 0..@$mysql ) { my $field1 = $mysql->[$idx]{field1}; }
Notes: If you specify an array in a scalar context, Perl decides you want to know how many elements there are in the array. The range operator is definitely a scalar context, it expects a number on the left and a number on the right. I frequently use scalar @array, so others will decipher what I'm doing more easily; some people think the superfluous 'scalar' is bad ( Hi Mike ).
Some people differentiate between 'for' and 'foreach'; they must love typing. I use 'for' for both, since Perl considers them synonyms.
You don't need to quote hash tags, you can use the bare text; similarly, the bare characters before a fat arrow are automatically taken as a string:
use 5.010; $tag = 'Homer'; my %h = ( $tag => 'woohoo!', Fred => 'YABA DABA DOO!' ); say Dumper(\%h); # outputs: # $VAR1 = { # 'Homer' => 'woohoo!', # 'Fred' => 'YABA DABA DOO!' # };
As Occam said: Entia non sunt multiplicanda praeter necessitatem.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Style and Preference on Loops
by eyepopslikeamosquito (Archbishop) on Aug 12, 2011 at 22:21 UTC | |
by jwkrahn (Abbot) on Aug 12, 2011 at 23:01 UTC | |
by eyepopslikeamosquito (Archbishop) on Aug 13, 2011 at 00:43 UTC | |
by TomDLux (Vicar) on Aug 15, 2011 at 13:50 UTC |