[lug] Perl Question..
Tkil
tkil at scrye.com
Thu Apr 17 19:54:51 MDT 2003
>>>>> "Tkil" == tkil <tkil at scrye.com> writes:
Tkil> 9. The more polite solution is to move the complex key
Tkil> calculation off to the side:
Heh. Probably the most "polite" method is really to use multiple
stages. I just really enjoy map / sort / grep type things.
So, for maintainable code, I'd probably do something more along the
lines of:
| my @info;
| foreach my $file ( glob '*.html' )
| {
| my ( $month, $year ) = split /\./, $file;
| my $key = sprintf "%04d-%02d", $year, int_month($month);
| my $html = qq|<a href="$file">$month - $year</a><br />\n|;
| push @info, [ $key, $html ];
| }
|
| foreach my $info ( sort { $a->[0] cmp $b->[0] } @info )
| {
| print $info->[1];
| }
Although even now I'd be tempted to do another dirty trick, by taking
advantage of the fact that our sort key are fixed length:
| my @info;
| foreach my $file ( glob '*.html' )
| {
| my ( $month, $year ) = split /\./, $file;
| my $key = sprintf "%04d-%02d", $year, int_month($month);
| my $html = qq|<a href="$file">$month - $year</a><br />\n|;
| push @info, $key . $html;
| }
|
| foreach my $info ( sort @info )
| {
| print substr $info, 7;
| }
So my full test program is now:
| #!/usr/bin/perl -w
|
| use strict;
|
| {
| my %MONTHS;
| @MONTHS{ qw( Jan Feb Mar Apr May Jun
| Jul Aug Sep Oct Nov Dec ) } = 1 .. 12;
|
| sub int_month ( $ )
| {
| my $in_abbrev = ucfirst substr $_[0], 0, 3;
| return $MONTHS{$in_abbrev} || 0;
| }
| }
|
| my @info;
| # foreach my $file ( glob '*.html' )
| foreach my $file ( grep { $_ } map { s/\s+\z//; $_ } <DATA> )
| {
| my ( $month, $year ) = split /\./, $file;
| my $key = sprintf "%04d-%02d", $year, int_month($month);
| my $html = qq|<a href="$file">$month - $year</a><br />\n|;
| push @info, $key . $html;
| }
|
| foreach my $info ( sort @info )
| {
| print substr $info, 7;
| }
|
| __DATA__
| August.1998.html
| December.900.html
| December.1999.html
| January.1997.html
| November.2003.html
And it still works:
| $ ./joey2.plx
| <a href="December.900.html">December - 900</a><br />
| <a href="January.1997.html">January - 1997</a><br />
| <a href="August.1998.html">August - 1998</a><br />
| <a href="December.1999.html">December - 1999</a><br />
| <a href="November.2003.html">November - 2003</a><br />
More information about the LUG
mailing list