Today’s Perl Lesson

Dec 7, 2009 / By John Scoles

Tags: , ,

One thing I find fascinating in Perl is that I am always seeing new ways to perform the same mundane task.

Today I had to output some tabular data, so I thought it would be nice if I alternated colours for each row. Easy enough in Perl—just create a hash with your colours as the value and then the swapping variable as the key, like this:

my %colours=(1=>'red', 0=>'green');
my $swap=1;

foreach $item (@stuff) {
    my $colour=$colours{$swap};
...

Then I though about how to flip the $swap value. I could simply use the tried and true—and like me—Luddite style:

 if ($swap == 1) {
    $swap = 0;
 }
 else {
    $swap = 1;
 }

Well, it’s easy to read at least. Alternatively, I could reach back to my roots and do something C-ish like this:

$swap = $swap == 1 ? 0 : 1;

This is a little more compact but also a little harder to read, and it doesn’t save any code steps. And anyway, this is Perl, so my colleague Yannick suggested this . . .

$swap=!$swap;

. . . which I had never seen before. This is what I went with as it saves steps and is easy to read.

No doubt there are other approaches out there?

2 Responses to “Today’s Perl Lesson”

  • You can try this:

    my %colours=(1=>’red’, 0=>’green’);

    for(my $i=0;$i<@stuff;$i++){
    ..
    my $colour=$colours{$i%2};
    ..
    }

    • …and from there realize that we don’t want a hash, but an array:

      my @colours= qw/ red green /;

      my $i;
      for my $s ( @stuff ) {
      ..
      my $colour=$colours[ $i++ % 2 ];
      ..
      }

      And to do without the indexing variable altogether, we can call on darker magic:

      my @colours= qw/ red green /;

      for my $s ( @stuff ) {
      ..
      my $colour=$colours[ --$| ];
      ..
      }

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>