Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

last character in string ?

by rimmern (Acolyte)
on Oct 01, 2001 at 13:35 UTC ( #115813=perlquestion: print w/replies, xml ) Need Help??

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

How do I get everything but the last character in a string ?

IE from $date="October " I'd want to get $date="October"

(I've tried removing the blank space and carriage returns but still the rogue space appears on the end of the string)


Replies are listed 'Best First'.
Re: last character in string ?
by davorg (Chancellor) on Oct 01, 2001 at 13:40 UTC

    chop will remove the last character from a string, but I wonder if that's really what you want to do.

    To remove all of the whitespace from the end of a string, use something like this:

    $string =~ s/\s+$//;

    "The first rule of Perl club is you don't talk about Perl club."

Re: last character in string ?
by MZSanford (Curate) on Oct 01, 2001 at 13:42 UTC
    Hmmm, any of the below should work :
    chomp($date); # remove newlines chop($date); # remove last char $date =~ s/\s*$//; # remove trailing spaces $date = substr($date,0,(length($date)-1)); # remove last char ($date) = $date =~ m/(.*)\s*$/; # i would imagine the slowest solution

    "They shall not overcome. Whoever told them that the truth shall set them free was obviously and grossly unfamiliar with federal law."
        -- John Ashcroft
      you suggested :

      $date = substr($date,0,(length($date)-1)); # remove last char

      It's worth noting that perl uses negative numbers to "count backwards" when dealing with string (and array, and probably many other surprising things) indexes, removing the need to do things like length($date)-1)). Code looks nicer and scans better for the effort.
      See Piercer's code below.

      Update : Wouldn't it be nice if push, pop and (un)shift worked on characters in a string? Yes, there's chop. that's true enough, but still.

        In regard to your update, you should check out Tie::CharArray


        You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)


        What fun :)

        my @words = grep({ref} @clever);
        sub version { print "I cuss your capitalist pig tendencies bad!\n" }
Re: last character in string ?
by Piercer (Beadle) on Oct 01, 2001 at 14:24 UTC
    Or you could use substr($string, 0, -1)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://115813]
Approved by root
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2023-11-29 05:10 GMT
Find Nodes?
    Voting Booth?

    No recent polls found