develooper Front page | perl.beginners | Postings from February 2002

Re: Crop string to x characters

From:
Briac Pilpré
Date:
February 17, 2002 14:42
Subject:
Re: Crop string to x characters
Message ID:
20020217224246.26487.qmail@onion.perl.org
On Sun, 17 Feb 2002 at 22:34 GMT, Gary Hawkins wrote:
> ------=_NextPart_000_02E4_01C1B7C0.2E6F3B50
> Content-Type: text/plain;
> 	charset="US-ASCII"
> Content-Transfer-Encoding: 7bit
> 
> How do I truncate a string to a particular number of characters?
> 
> This is expensive:
> 
> $shortdescription =~
> s/(............................................................................
> ....................................... ).*/$1/;

You can use the substr() function, or optimize your regex:

#!/usr/bin/perl -w
use strict;

my $string;

# with substr
$string = "hello word";
$string = substr($string,0,4);
print "substr: $string\n";

# with a regex
$string = "hello word";
$string =~ s/^(.{4}).*/$1/;
print "regex: $string\n";
__END__


-- 
briac
 << dynamic .sig on strike, we apologize for the inconvenience >>




nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About