I wrote this short subroutine to left, center, right-align a multiline string.
How can I make it better (shorter, prettier, optimized)? Can you offer some suggestions?
#!/usr/bin/env perl
use strict;
# A bit of text
$_ = <<END;
Lorem ipsum dolor sit amet consectetur adipiscing elit
Curabitur pretium odio dictum nisl posuere, vitae mollis nibh facilisis
Curabitur tempus tincidunt ante eget facilisis
Pellentesque ut accumsan dui, nec semper odio
Ut libero lacus, fermentum quis ultricies quis, tempus nec augue
Mauris tincidunt hendrerit accumsan
END
# Test each alignment case
for my $align ('left', 'center', 'right') {
print align($_, $align)."\n";
}
# Alignment subroutine
sub align {
local $_ = shift;
my ($align) = @_; # Text to align, Alignment type
my $re = qr/^(.*)/m;
s/^[ \t]+|[ \t]+$//gm; # Remove trailing/leading spaces
# Get longest line
my $max = 0;
length($1) > $max and $max = length($1) while /$re/g;
if ($align eq 'left') { s|$re|$1 . " " x ($max-length($1))|ge }
elsif ($align eq 'center') { s|$re|" " x (($max-length($1))/2) . $1|ge }
elsif ($align eq 'right') { s|$re|" " x ($max-length($1)) . $1|ge }
return $_;
}