in reply to Re: Check last character of a string
in thread Check last character of a string

Mmmm

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.

Replies are listed 'Best First'.
Re^3: Check last character of a string
by dHarry (Abbot) on Aug 07, 2008 at 09:09 UTC

    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" ; }

      For the sake of a shorter program, one less function call, a negated regexp and completely ignoring the one-liner posted Corion very early in this thread

      use strict; use warnings; my $location = "some location"; my $dirchar = "\\"; $location = $location.$dirchar if ($location !~ /{$dirchar}$/); print "Hier ist es : ".$location."\n";

      I may have approached the problem the same way as you are when I first started learning Perl. Now I would tend to use the above. I don't find regexp's easy but perlrequick is a good starting point before moving on to doc::/perlre and Mastering Regular Expressions