THE WORLD DISCUSSES #PYTHIAN ON TWITTER. HAVE A QUESTION? USE OUR HASHTAG AND ASK AWAY.

Today’s Perl Lesson

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

  1. 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

Start NowWith Pythian - database design, management and emergency handling capabilities...

Live Updates

pythian: RT @sheeri: #confoo talk "Bending Queries to your Will with EXPLAIN" slides http://bit.ly/explainslides & handout
more



Testimonials

  • Serge Racine

    DBA, Brookfield Energy

    We are very satisfied by the service given to us by Andre and Shakir in support of our recent data quality and reorganization initiative.... more