http://qs1969.pair.com?node_id=1136534


in reply to RE: split function not working as expected[SOLVED]

I believe you're running into some *special* cases when using a double-quoted literal and the pipe symbol. Normally the pipe symbol would be used for ORing your pattern. "i|A" would split on the characters i or A. When you want the pattern to match the pipe symbol, you would need to escape it with a backslash "\|" - however in this case when you double-quote and backslash, it is not escaped -- you need to single quote and backslash. I normally opt to use a regex as the PATTERN in split -- to me it's more readaable:

my( $first, $second ) = split /\|/, $string;
but that's just me.

-derby

Replies are listed 'Best First'.
Re^3: split function not working as expected
by AnomalousMonk (Archbishop) on Jul 28, 2015 at 03:22 UTC

    My personal preference is to "escape" such metacharacters (and the space character) within a character class: [|]. This avoids incipient LTS and is also written the same in all variations:  /[|]/  "[|]"  '[|]'


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

Re^3: split function not working as expected
by lonewolf28 (Beadle) on Jul 28, 2015 at 04:10 UTC

    Even if i backslash it i get the same....

    my $string = 'osSE5Gu0Vi8WRq93UvkYZCjaOKeNJfTyH6tzDQbxFm4M1ndXIPh27wBA + rLclpg| 3 35 27 62 51 27 46 57 26 10 46 63 57 45 15 43 53'; my ( $first, $second ) = split ( "\|", $string ); say "first:", $first; say "second:", $second; output: first:o second:s

      c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $s = 'first|second|third'; my @ra = split '[|]', $s; dd \@ra; " ["first", "second", "third"]
      Also works with  "[|]" and  /[|]/

      Update: The reason  "\|" doesn't work is that in double-quote interpolation, the  \ (backslash) acts, in this case, on the  | (pipe) to produce a literal pipe. Double-quotish interpolation would need a doubled backslash to yield a single literal backslash in the compiled string:

      c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $s = qq{\|}; print qq{:$s:}; ;; my $t = qq{\\|}; print qq{:$t:}; " :|: :\|:
      That's why it's generally better to use  qr{pattern} to compile a regex. (I use  qq{...} in the example because Windows command line uses "..." to quote everything and  qq{...} reduces the need for backslashes.) Contrast with  '\|' and  '\\|' Please see Quote and Quote-like Operators and Quote-Like Operators.


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

      Right ... as I said, if you want to use quotes instead of a regex pattern, use single quotes. Double quotes cause interpolation to happen which you don't want here.

      -derby