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

I need to know, how many backslashes are in a variable, but with 'print' it gives me unclear output on the Linux console. I use the following code:

$i1 = '1\2'; $i2 = '1\\2'; $i3 = '1\\\2'; $i4 = '1\\\\2'; print "#$i1#$i2#$i3#$i4#\n";

It gives me the following output:

#1\2#1\2#1\\2#1\\2#

The first 2 and the last 2 variables give the same output. But I must know, how many backslashes in a row are in the variable. Any hints?

Replies are listed 'Best First'.
Re: print backslash in variable
by hippo (Archbishop) on Aug 17, 2015 at 16:06 UTC

    The method you are using to set the variables (enclosing in single quotes) means that the backslashes are escaped by other backslashes. Your print statement is a good idea and is genuinely showing you the correct values of the variables. A quick read of Quote and Quote-like Operators may help to clear things up for you.

      ... more exactly, first entry in subsection Quote-Like Operators (without "Quote and"). I guess this (and the "Regexp" and "Gory details" sections) should be subheadings under "Quote and Quote-like".
Re: print backslash in variable
by AnomalousMonk (Archbishop) on Aug 17, 2015 at 17:16 UTC
    ... I must know, how many backslashes in a row ...

    A way:

    c:\@Work\Perl\monks>perl -wMstrict -le "my $s = '\\\\\---\--\\\\---\\--\\\-'; print qq{'$s'}; ;; printf ' %d', $_ for map tr{\\}{}, $s =~ m{ \\+ }xmsg; " '\\\---\--\\---\--\\-' 3 1 2 1 2

    Update: map expression was  scalar(tr{\\}{\\}) but I realized scalar wasn't necessary.


    Give a man a fish:  <%-{-{-{-<

Re: print backslash in variable
by johngg (Canon) on Aug 17, 2015 at 21:47 UTC

    You could initialise your variables using the \x?? hexadecimal character values to avoid confusion.

    $ perl -E ' say for ( qq{a\x5cb}, qq{a\x5c\x5cb}, qq{a\x5c\x5c\x5cb}, qq{a\x5c\x5c\x5c\x5cb}, );' a\b a\\b a\\\b a\\\\b $

    I hope this is helpful.

    Update: Another way would be to use chr.

    $ perl -E ' > @arr = map { q{A} . do { chr 0x5c } x $_ . q{B} } 1 .. 4; > say for @arr;' A\B A\\B A\\\B A\\\\B $

    Cheers,

    JohnGG