Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Smart Substrings

by elusion (Curate)
on Apr 03, 2001 at 03:54 UTC ( [id://69152]=note: print w/replies, xml ) Need Help??


in reply to Smart Substrings

I would do it like this:
$string =~ s/^(.{15}).+$/$1/;
To split between words and add .. I'd use:
$string =~ s/^(.{1,15})\s*.*$/$1.../;
This assumes you want a string 15 chars long + the "...", if there's not a space in the 15 chars it chops it there anyways.

- p u n k k i d
"Reality is merely an illusion, albeit a very persistent one." -Albert Einstein

Replies are listed 'Best First'.
Re: Re: Smart Substrings
by MeowChow (Vicar) on Apr 03, 2001 at 05:09 UTC
    Your first code snippet is a good example of bringing out the regex chain-gun when a simple substr would do:
    my $short = substr $string, 0, 15;
    This is equivalent, but faster and more readable. Don't use a regex unless you actually need it.

    Your second snippet doesn't split on words. You would need to change the \s* to a \s+ for it to do that, but then it would break on a starting word greater than 15 chars.

    I don't mean to offer harsh criticism, but one of my pet peeves is seeing regexes used when a simple index/substr would do.

       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print

      Why would you keep a peeve as a pet? Wouldn't a dog or a cat be more fun?

      (Sorry, couldn't resist ;^)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://69152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-26 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found