3 ms·
Could you elaborate a little? I ask because the Perl 5 code looks a lot like the Perl that I write. I'd like to improve, but the existing Perl code that I'm wri
by bglazer 12y ago
Could you elaborate a little? I ask because the Perl 5 code looks a lot like the Perl that I write. I'd like to improve, but the existing Perl code that I'm writing on top of is really bad. Like really, really bad. I don't have much quality Perl to compare against.
- Mithaldu 12y agoTwo examples: $freq{substr $grade{$_}, 0, 1}++ for keys %grade; better: $freq{$_}++ for map { substr $_, 0, 1 } values %grade; best: my @letters = map { substr $_, 0, 1 } values %grade; $freq{$_}++ for @letters; ---------------------------- and open my $fh, '<:utf8', "grades.txt" or die "Failed to open file: $!"; my %grade; while (<$fh>) { m/^(\w+) \s+ ([A-F][+-]?)$/x or die "Can't parse line '$_'"; $grade{$1} = $2; }; better: use 5.010; use IO::All -binary, -utf8; my $line_format = qr/ ^ # line start (?<student>\w+) # name \s+ # gap (?<grade>[A-F][+-]?) # grade $ # line end /x; my $fh = io->file("grades.txt"); my %grade; while (my $line = $io->getline) { die "Can't parse line '$line'" if $line !~ $line_format; $grade{$+{student}} = $+{grade}; }
- hvs 12y agoVery nicely done. I use Perl in my everyday job, and its nice to see that some people still know how to write good Perl.
- Ultimatt 12y ago5.10 in production? Surely you're joking! 5.8 or bust.
- pjfl 12y agoYou should have use strict; use warnings; then you would have noticed the my $fh and the $io->getline error
- Mithaldu 12y agoDammit, you're right. I was working in a buffer without perl instrumentation enabled because i was composing a comment, not a script. Now i can't edit the comment anymore. :/