Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Check last character of a string

by theroninwins (Friar)
on Aug 06, 2008 at 09:10 UTC ( #702570=perlquestion: print w/replies, xml ) Need Help??

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

Hi My problem is that I need to check the last character of a sting. It needs to be \ or I have to add it.
if (-d $location){ check if $location ends with \ .. or if not add it.. }
I tried with RegEx but that doesn't work Anyone an idea?? Thx UPDATE: Great guys thanks.. now it works :
my $var = substr($location,length($location)-1,1); print "\n\nVAR::: $var\n\n"; if ($var eq "\\"){ print "HIER IS ES\n\n"; } else{ $location = $location."\\"; print "NEU:: $location\n\n" ; }
does it :-)

Replies are listed 'Best First'.
Re: Check last character of a string
by Corion (Patriarch) on Aug 06, 2008 at 09:22 UTC

    It works for me. What did you try and how did it fail for you?

    See perlre for the various ways of how to quote characters in regular expressions.

    perl -le "for (@ARGV) { printf qq('$_' does %s end with a backslash\n) +, /\\$/ ? '' : 'not'}" c:\ c:\foo
Re: Check last character of a string
by Perlbotics (Bishop) on Aug 06, 2008 at 09:23 UTC
    Do you mean  $location .= '\\' unless $location =~ m(\\$); ? (Variations: chomp and m(\\\Z) )
      Well it fails as in I need the string to end with \ because I use it as a folder name adding filenames to it. So when the ARGV does not end with \ the adding goes wrong.

        Have you thought about using File::Spec->catfile instead?

        Hi, for me this works:
        #!/usr/bin/perl use strict; my @tests = qw( path1 paht2\ ); for my $location (@tests) { print "before: '$location'\n"; $location .= '\\' unless $location =~ m(\\$); print "after: '$location'\n"; } __END__ before: 'path1' after: 'path1\' before: 'paht2\' after: 'paht2\'
      yes but now i add it if it is there or not. I only need to add it when it is not there.
Re: Check last character of a string
by pjotrik (Friar) on Aug 06, 2008 at 11:12 UTC
    How about testing and adding in one step?
    $x =~ s/([^\\])$/$1\\/
      Or without a capture:

      perl -wMstrict -le "for (@ARGV) { print; s{ (?<! \\) $ }'\\'xms; print } " with\ sans with\ with\ sans sans\
Re: Check last character of a string
by LesleyB (Friar) on Aug 06, 2008 at 09:25 UTC

    I take it you mean 'string' not 'sting' and you didn't declare the regular expression you tried so I am left wondering if you tried one at all.

    I'd probably try something like =~ /\\$/ which is a very simple (but untested) regexp

    Try reading perlrequick or perlre

    Update: corrected reference and use of incorrect character

Re: Check last character of a string
by Anonymous Monk on Aug 06, 2008 at 15:59 UTC
    BTW, the concern about a backslash in a path suggests the OPer is running under Windows.

    Windows seems to have the 'feature' that it doesn't care how many '\' characters separate directory names in a path. Would unconditionally appending a '\' work just as well?

      AFAICR, most operating systems have that 'feature' ;-)
Re: Check last character of a string
by theroninwins (Friar) on Aug 06, 2008 at 09:35 UTC
    This is what I treid before:
    my $var = substr($location,length($location)-1,1); print "\n\nVAR::: $var\n\n"; if ($var == "\\"){ print "HIER IS ES\n\n"; } else{ $location = $location+"\\"; print "NEU:: $location\n\n" ; }

      Did you see any warnings? Warnings help you spot problematic points in your code.

      Perl does not compare strings for equality using ==. Maybe you want to use eq?

      Perl does not use + to concatenate strings. Maybe you want to use . ?

      The "==" hurts my eyes;-) If you change it into "eq" it will work my son.


      I'm still plodding along in 5.8 not even tried 5.10 yet so if ($var == "\\") doesn't even look like a regular expression to me and I know that I use strncmp in C.

      And the logic is wrong; even using eq you'll find that logic will test if your string is equal to "\" and you originally said you wanted to test whether the end of the string contained '\'.

      Try using if ($var =~ /\\$/){ instead.

      See perlrequick for an explanation of the $.

      Update: Sorry didn't read the code properly to realise you were grabbing the last character of the string before checking it. The '==' threw me, Your Honour! I don't think it is necessary to do that. The above regexp should work for any string and should detect a '\' at the end of the whole string. It should work anyway but you don't need to strip that char out to examine it.

        For the sake of completeness the code I used to verify that it worked with the "eq" operator. And for the record: I'd prefer a RegExp myself in this situation;-)

        use strict; use warnings; my $location = "some location\\"; my $var = substr($location,length($location)-1,1); if ($var eq "\\"){ print "HIER IS ES\n\n"; } else{ $location = $location."\\"; print "NEU:: $location\n\n" ; }
Re: Check last character of a string
by rovf (Priest) on Aug 07, 2008 at 08:44 UTC
    I need to check the last character of a sting. It needs to be \ or I have to add it.

    I wrote a function some time ago which solved a more general problem: uncomp($s,$tail) returns $s if it already ends in $tail, and returns $s.$tail otherwise. In my case, I more often needed it to ensure that the string is ended in a newline, so I made this as a default: unchomp($s) is equivalent to unchomp($s,"\n"), but of course you can easily adapt this to your path separator.

    sub unchomp { my ($s,$suffix) = (@_,"\n"); die("unchomp called on undef string") unless defined($s); die("unchomp called for undef suffix") unless defined($suffix); my $slen=length($suffix); substr($s,-$slen) eq $suffix ? $s : ($s.$suffix) }

    Ronald Fischer <>

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2022-05-21 19:44 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (77 votes). Check out past polls.