Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

This isn't homework... But it might look that way. It's a project I'm working on for work.

This works OK but looks very inefficient... All the 'or' statements are mucking me up and I can't figure out a slicker way to do this. Take a look and see if you can do better (I'm sure at least some of you can). This is under use strict; and -w.

This code eats a text file and spits out values for each of the variables at one minute intervals, using UNIX time. The parsing is nice, this is the ugly bit - the output.

# Figure out the first timestamp foreach my $bar (sort keys %master) { $j = $bar; last; } # Figure out the last timestamp foreach my $bar (reverse sort keys %master) { $l = $bar; last; } do { my $out; $out .= "$j,"; $out .= $master{$j}{'CCMT'} || '0'; $out .= ","; $out .= $master{$j}{'CCOA'} || '0'; $out .= ","; $out .= $master{$j}{'CDEC'} || '0'; $out .= ","; $out .= $master{$j}{'CFST'} || '0'; $out .= ","; $out .= $master{$j}{'CREF'} || '0'; $out .= ","; $out .= $master{$j}{'CRSP'} || '0'; $out .= ","; $out .= $master{$j}{'CVEH'} || '0'; $out .= "\n"; print $out; $j += 60; } while $j <= $l;

Replies are listed 'Best First'.
Re: Golf, Anyone? Stupid output questions
by VSarkiss (Monsignor) on Apr 17, 2002 at 02:38 UTC

    If you need them in a specific order:

    my @keys = qw(CCMT CCOA CDEC CFST CREF CRSP CVEH); do { print $j, ',', join(',', map { master{$j}{$_} || '0' } @keys), "\n"; $j += 60; } while $j <= $l;
    One note: I think do while is a really icky construct, but I wanted to reproduce your code.

Re: Golf, Anyone? Stupid output questions
by belg4mit (Prior) on Apr 17, 2002 at 02:34 UTC
    First off, why are you doing two sorts? Sorts are pretty damn expensive (or so I'm told). Especially in this case, I would imagine, since hash lookups on anagrams (act, atc, cat, cta, tat, tca) are particularly slow. Being timestamps they are restricted to a 10 character set, and most likely be all of the same length, thusly ensuring that a portion of a decent sized will be anagrams.
    ($j, $l) = (sort keys %master)[0,-1];
    Second
    #Might go with a C-style for-loop here. while($j <= $l){ for my $elem (qw(CCMT ...)){ $out .= "," . ($master{$j}{$elem} || '0'); } $j+=60; }

    --
    perl -pe "s/\b;([mnst])/'\1/mg"

Re: Golf, Anyone? Stupid output questions
by crazyinsomniac (Prior) on Apr 17, 2002 at 02:34 UTC
A reply falls below the community's threshold of quality. You may see it by logging in.