Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Efficienty truncating a long string

by PodMaster (Abbot)
on Dec 18, 2003 at 09:28 UTC ( #315470=note: print w/replies, xml ) Need Help??


in reply to Efficienty truncating a long string

See "Functions for SCALARs or strings" in perlfunc, in particular substr ==> `perldoc -f substr'

MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
** The third rule of perl club is a statement of fact: pod is sexy.

  • Comment on Re: Efficienty truncating a long string

Replies are listed 'Best First'.
Re: Re: Efficienty truncating a long string
by dino (Sexton) on Dec 18, 2003 at 09:33 UTC
    Well I've looked at substr and can understand its normal non lvalue usage, but as far as I can see its a copying operator, returning a substr of the original. I want to truncate a string without the copying overhead. The lvalue version seems to be ok, but I dont quite understand how to use it to truncate a string. Any suggestions?
      I don't know whether substr is optimized not to bother returning anything in void context (probably is), but this is how you do it
      my $long_string = 'string' x 5; print $long_string,$/; substr( $long_string, 6 ) = ''; # truncate to 6 characters # # same thing, only using 4 arg substr # substr( $long_string, 6, length($long_string) - 6, '' ); # print $long_string,$/; __END__ stringstringstringstringstring string

      MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
      I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
      ** The third rule of perl club is a statement of fact: pod is sexy.

        4-arg substr isn't optimized for void context. It will set up the replaced string to be returned regardless.

        The lvalue substr doesn't actually return the string but a special lvalue indicating the offset and length. Creating this and setting it to '' involves a fair amount of overhead.

        Which is actually more efficient will probably depend on how much you are truncating.

        Ty, How embarrasing, that simple eh? Thanks again, sigh. :)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2023-09-21 19:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?