Daemon Logging Percentages and Playing with Ruby Idioms
While digging in to some large log files recently I needed to work out which daemons were causing the most noise, so I wrote a little perl script called daemon_percentages.pl. It was short, ran quickly and did what I wanted. And then my lunch plans were cancelled due to rain.
With nothing but boredom, a newly compiled version of ruby and the google homepage at my side I decided to write a version in ruby. And then I realised how long it’s been since I last looked at ruby. After slightly longer than the perl version took, and with a couple of false starts, I ended up with daemon_percentages.rb.
I had forgotten how much I disliked
ri. It feels slower
perldoc and I find it awkward to use. Then I hit the
lack of a post-increment operator; while I understand the reasons for its
omission I’ve got used to having it, so that took a couple of minutes to
debug. And then the biggie for me, a lack of hash key autovivification.
I’d forgotten how much of a perlism it is and so I spent a little while looking at different ways to do it (and got some good pointers from Will Jessop). In the end I tried the following:
# option 1 if tally.has_key? daemon tally[daemon] += 1 else tally[daemon] = 1 end # option 2 tally[daemon] = 0 unless tally.has_key? daemon tally[daemon] += 1 # option 3 tally[daemon] = (tally.has_key? daemon) ? tally[daemon] + 1 : 1
Option 1 felt too long, I didn’t like option 2 when I reread it as the code seemed to imply I’d decided something and immediately then changed my mind so I settled on option 3. Although it’s a little more complex (and denser) it’s such a common thing for me to use I’d rather have it on a single line and gloss over the syntax as it becomes more familiar.
While I had some small teething problems I do like the look of the ruby code and apart from the missing perlisms it felt quite natural to write. I’m not willing to jump ship just yet (CPAN is still too useful) but I think I’ll be writing more of my personal tools in ruby.