The wonder that is grep

CromeDome on 2003-07-16T05:15:47

I've been programming Perl for. . . 2 years now, I think. And that entire time I've been wondering what in the hell I'd use grep for. Today I discovered it :) I have no idea what prompted me to think of it, but it made life sooooooo much easier.

Rather than try to explain what I was doing, I'll let the code speak for itself:

my @days = qw(Monday Tuesday Wednesday Thursday Friday Saturday Sunday); my @hours = qw(7a8a 8a9a 9a10a 10a11a 11a12p 12p1p 1p2p 2p3p 3p4p 4p5p 5p6p 6p7p 7p8p 8p9p 9p10p); my @rows;

foreach my $day (@days) { my @times = $request->param($day);

# Increment the total number of hours $count += scalar @times;

# Iterate over the list of hours my %row; my $hour_num = 1; $row{DAY} = $day;

foreach my $hour (@hours) { my $fill_char;

# Was this hour selected? my $found = grep(/$hour/, @times); if($found) { $fill_char = "x"; } else { $fill_char = " "; }

# Fill the hash of times for this day $row{"HOUR$hour_num"} = $fill_char; ++$hour_num; }

# Write a line out to the table push @rows, \%row; }


The end result of this got pushed out to an HTML::Template. Check out the first table here to get an idea of what we're producing.

I love grep!


good code

spur on 2003-07-21T05:03:50

You have a nice and consistent style of Perl coding. Your code is very easy to understand by just reading it (and the embedded comments).

Way to go !