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:
[perl] my %colours=(1=>’red’, 0=>’green’);my $swap=1;
foreach $item (@stuff) {
my $colour=$colours{$swap};
…
[/perl]
Then I though about how to flip the $swap
value. I could simply use the tried and true—and like me—Luddite style:
$swap = 0;
}
else {
$swap = 1;
}
[/perl]
Well, it’s easy to read at least. Alternatively, I could reach back to my roots and do something C-ish like this:
[perl light=”true”] $swap = $swap == 1 ? 0 : 1;[/perl]
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 . . .
[perl light=”true”] $swap=!$swap;[/perl]
. . . 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 Comments. Leave new
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[ –$| ];
..
}