Today’s Perl Lesson

Posted in: Technical Track

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?

email

Interested in working with John? Schedule a tech call.

2 Comments. Leave new

Romeo Vasileniuc
December 7, 2009 7:42 pm

You can try this:

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

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

Reply
Yanick Champoux
January 5, 2010 4:07 pm

…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[ –$| ];
..
}

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *