The Oft-Overlooked and the Sometimes-Neverused

Perl has so many useful builtins that most people who use the language probably only use a fraction of what's available. Every year or so I like to peruse perlfunc and perlsyn as a refresher. Yet in years and years of hacking Perl code, there are a few in there that I will never use. I surprised myself the other day by reaching for the loop control command redo. It occurred to me that while I use other loop controlling things like next and last constantly, I couldn't remember a single time before when I have ever had to redo an iteration. For the curious, here's the astonishingly simple scenario where it came up.

When you're writing applications against Twitter's REST API, they ask you to be polite and only execute a certain number of HTTP requests in a certain amount of time. The certain number depends on their current server load, and so you can't just set a time limit in your script and forget it. Instead, you have to make your requests and then pause if Twitter asks you to slow down. If they want you to ease back on the throttle, they send a custom HTTP status with a header indicating how many seconds you should wait. Here's how I handle it.


foreach my $tag( keys %tags ) {
....
my $res = $ua->get( $url );
unless( $res->is_success ) {
my $status = $res->code;
if ( $status == 420 ) {
# we are being rate-limited
my $wait = $res->header( 'Retry-After' ) || 31;
warn "API rate-limit - waiting for $wait secs...";
sleep $wait;
redo;
}
....
}

my $json = $res->decoded_content;
....
}

This loops over a bunch of Twitter hash tags and asks for some information about each one. If Twitter gets antsy, instead of sending the information with a HTTP status of 200, it sends a "slow down" message with an HTTP status of 420. The script sits there and does nothing for the allotted number of seconds and then repeats the loop iteration to hopefully get the information that resulted in an error last time.

What language features have you never used, despite being aware of them, or were surprised to use for the first time after much experience?

3 Comments

I recently had to use a continue block for the first time ever. Never thought I'd need that.

Recently, I was raving about do-given in the upcoming Perl 5.14 and I was surprised at how many of my coworkers never use do.

Leave a comment

About Mike Friedman

user-pic Mike Friedman is a professional computer programmer living and working in the New York City area.