Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Truncate string without substr or length

by spivey49 (Monk)
on Oct 16, 2008 at 17:49 UTC ( #717539=perlquestion: print w/replies, xml ) Need Help??

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

Given a vairable legnth string like "4.3.25" or "1.4.3.25" I need to truncate the ".25", preserving the "4.3" or "1.4.3".

I've been using substr and length for a quick and dirty cludge, but I'd like to replace it with a single regex. Any suggestions?

  • Comment on Truncate string without substr or length

Replies are listed 'Best First'.
Re: Truncate string without substr or length
by moritz (Cardinal) on Oct 16, 2008 at 17:51 UTC
    $str =~ s/\.\d+$//;

    See perlretut for a gentle introduction to regexes.

    That removes the last period followed by a number, at the end of the string. If you only want to remove .25, use s/\.25// instead.

Re: Truncate string without substr or length
by ikegami (Pope) on Oct 16, 2008 at 17:54 UTC

    substr and length? substr and rindex!

    $s = substr($s, 0, rindex($s, '.'));

    The regexp equivalent is

    $s =~ s/\.[^.]*$//;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://717539]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2019-12-15 15:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?