Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All, just a quick question, I'm wanting to display a field which can only be so long because it will mess up the html tables, so if
$string = 'ewfwfrgergwgwethwrthwrheargaewrfdsgfdse';

Is it possible to display the first 20 charachters of that string and then '..' ?

Any help would be appreciated, thank you

Replies are listed 'Best First'.
Re: Cutting down a string
by lhoward (Vicar) on Nov 10, 2001 at 02:28 UTC
    $string=substr($string,0,20).'..' if length($string) > 22;
      substr( $string, 20 ) = '..' if length($string) > 22;

      or even

      $string = sprintf( "%20s..", $string ) if length($string) > 22;

        Nice, but not quite right:
        $string = sprintf( "%.20s..", $string ) if length($string) > 22;
        --
        John.

      thank you very much
Re: Cutting down a string (boo)
by boo_radley (Parson) on Nov 10, 2001 at 04:37 UTC
    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/;$_ }

      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)},"

Re: Cutting down a string
by jmcnamara (Monsignor) on Nov 10, 2001 at 21:42 UTC

    This is for boo_radley's golf challenge, although the output differs slightly from his example. 60 chars:
    sub squash { ($a,$b)=@_;$b-=3;substr$a,0,-$b/2,substr($a,0,$b/2)."...";$a }
    --
    John.