in reply to Cutting down a string

timtowdi! all purpose-- can be run through strings shorter than 20 characters with no bad effect.
my $foo="asdhflakjsdfhlaksjdfhlaksdjfhalks"; $foo =~ s/(.{20}).{3,}/$1../; print "-"x 20, "\n"; print $foo, "\n"; my $foo="asdhflakjsdfhlaksjdfh"; $foo =~ s/(.{20}).{3,}/$1../; print "-"x 20, "\n"; print $foo,"\n";

friendly golf challenge : given a string, and a length, truncate the string in the middle, using 3 periods (an ellipsis) to indicate the truncation. The truncation must be even, that is, the same number of characters must appear on each side of the ellipsis, plus or minus 1. The length given should be the final length of the string. Length will always be less than the string.
example  f("Just another perl hacker",11) = "just...cker"
example  f("Just another perl hacker",12) = "just ...cker" or "just...acker", depending on your preference. update 71 chars :
use integer; my $foo="Just another perl hacker"; print f2("Just another perl hacker",12); sub f2 { ($_,$l)=@_;$s=$l-3;$n=$s/2;$m=$n+($s&1);s/(.{$m}).*(.{$n})/$1...$2/;$_ }

Replies are listed 'Best First'.
Friendly golf challenge (was Re: Cutting down a string (boo))
by Sidhekin (Priest) on Nov 15, 2001 at 00:05 UTC

    For boo_radley's golf challenge, the Sidhekin takes jmcnamara's solution, fixes up the output to match the specs, and trims to 47 characters ... using no modules (other than optionally strict and warnings).

    use strict; use warnings; my $foo="Just another perl hacker"; print f("Just another perl hacker",11); print f("Just another perl hacker",12); sub f { ($a,$b)=@_;$b-=3;substr$a,$b++/2,-$b/2,"...";$a }

    The Sidhekin
    print "Just another Perl ${\(trickster and hacker)},"