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

    for my $idx ( 0..@$mysql ) {
    Of course, that should read:
    for my $idx ( 0..@$mysql-1 ) {

      No, it should read:

      for my $idx ( 0..$#$mysql ) {

        Though my version was not incorrect, I agree this is probably a better alternative here.

        Generally, I dislike the ungainly $#some_array syntax and it's rarely needed. For example:

        $some_array[$#some_array]
        is better written as:
        $some_array[-1]
        because, apart from the unpleasant-to-read $#some_array, the second form avoids the duplication of some_array.

      Thank you.

      As Occam said: Entia non sunt multiplicanda praeter necessitatem.