Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • I don’t know if the real code did something significantly different, but to me that’s just an example against consuming when you merely need to iterate. Or more abstractly: “avoid side effects.” I can’t remember ever having run into this sort of issue.

    I always cringe when I see people use shift on @_ – the only time I do that is when I really intend to modify the array, which boils down to my $self = shift; and precious little else.

    • by Ovid (2709) on 2005.08.31 13:02 (#42992) Homepage Journal

      I didn't show all of the code. There's a relatively common idiom of treating an array like a set of pairs, or an ordered hash:

      while (defined (my $key = shift @array)) {
        my $val = shift @array;
        # do something
      }

      In this case, this data needs to be represented as an array (hence my not using an ordered hash) except in this one odd corner case. Due to the nature of the code, this must always be the last step, so I didn't think destroying the array would be bad. I don't like it and it's definitely a code smell but it has to do with the way we receive external requests. Another option is to iterate over the array by 2:

      for (my $i = 0; $i < @array; $i += 2) {
        my ($key, $value) = @array[$i, $i + 1];
        # do something
      }

      I suppose the latter syntax is not as bad as I thought, but I hate C-style for loops as it's so easy to write them incorrectly.

      • Ah – yeah, stepping through an array in steps of two is annoyingly complicated, and I admit to having used consumption to iterate in those cases as well:

        while( my ( $k, $v ) = splice @array, 0, 2 ) {
            # ...
        }

        And you’re right about C-style loops, I avoid them like the plague myself.

        Hmm, what would be a good idiom to establish for the purpose… maybe this?

        for my $i ( 0 .. $#array / 2 ) {
            my ( $k, $v ) = @array[ $i * 2, $i * 2 + 1 ];
            # ...
        }

        Cumbers