Wednesday, November 21, 2007

Perl simple code

Strings

How to strip blank space from the beginning/end of a string?

Simplest method:
$string =~ s/^\s*(.*?)\s*$/$1/;
Not only is this unnecessarily slow and destructive, it also fails with embedded newlines. It is much faster to do this operation in two steps:
$string =~ s/^\s+//;
$string =~ s/\s+$//;

Or more nicely written as:
for ($string) {
s/^\s+//;
s/\s+$//;
}
This idiom takes advantage of the foreach loop's aliasing behavior to factor out common code. You can do this on several strings at once, or arrays, or even the values of a hash if you use a slice:
# trim whitespace in the scalar, the array,
# and all the values in the hash
foreach ($scalar, @array, @hash{keys %hash}) {
s/^\s+//;
s/\s+$//;
}

Mail

How to decode an email subject.
use MIME::Base64;
if ($subject =~ /^=\?[\w-]+\?B\?(.*)\?=$/) {
$subject = decode_base64($1);
}

No comments: