$string=substr($string,0,20).'..' if length($string) > 22;
| [reply] [d/l] |
substr( $string, 20 ) = '..' if length($string) > 22;
or even
$string = sprintf( "%20s..", $string ) if length($string) > 22;
| [reply] [d/l] [select] |
Nice, but not quite right:
$string = sprintf( "%.20s..", $string ) if length($string) > 22;
--
John.
| [reply] [d/l] |
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/;$_
}
| [reply] [d/l] [select] |
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)}," | [reply] [d/l] [select] |
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.
| [reply] [d/l] |