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 (Patriarch) 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/\.[^.]*$//;