May 2010 Archives

Stripping color codes in irssi scripts

So you're writing an IRC script for irssi and you want to strip formatting codes (including colors, bold, underline, etc) from some variable. This is possible with s///, and google will show many (usually not very readable) examples.

But there's an easier way: irssi has an undocumented function called Irssi::strip_codes that does all the work for you. And since irssi exports all functions into your script's namespace unconditionally, you don't even need to type the Irssi:: part:

my $clean = strip_codes($dirrrty);

This will remove so-called “mIRC colors”, irssi's internal formatting codes, and ANSI color sequences.

No semicolon after return values

Perl lets you omit semicolons at the end of a block. That is, you can treat ; as a statement separator, not a terminator, as in Pascal.

OK, but why would you want to do that? The advantage of terminating each statement is that you don't need to do anything special for the first and last lines: You can insert or remove lines at any point without worrying about the rest of the code. Why throw that away?

Because sometimes it doesn't make sense to add code at the end. Consider this code:

sub foo {
  my ($s) = @_;
  $s =~ s/%/%%/g;

The last statement $s is the return value. Adding statements after it could silently break this function. By omitting the last semicolon I can make the code a bit more robust, because now I get a syntax error when I try to put more code at the end without paying attention.

Maybe you don't use this form of code, though. Maybe you always write an explicit return. In that case any following code is silently ignored, so in the above scenario you wouldn't break anything, but your changes wouldn't have any effect either.

And there's another case that affects everyone who writes modules. Files loaded by require (directly or indirectly via use) need to return a true value. Most people simply write 1; at the end of their modules. I think it makes sense to omit the ; here as well, because nothing should come after it.

I've actually seen people cargo-cult module code, putting 1; in the middle of their Perl files. For those people: 1; doesn't make sense unless it's the last statement in a file and that file is a module. Everyone: you should end your modules with 1, not 1;.

(That's what I think, anyway. I hope this posting makes some sense.)

About mauke

user-pic I blog about Perl.