http://qs321.pair.com?node_id=11104559


in reply to Re: List comparison problem
in thread List comparison problem

The reason of the problem is that when you run:
$H_count ++ and ...
for the first time, the post increment operator sets $H_count to 1 and returns 0, i.e. a false value. Therefore, the statement following the and operator is not executed. The next time you run the same post-increment statement, it will return 1 (and subsequently other true values) and it will work fine as shown in the following test under the Perl debugger:
DB<1> $h++ and print "foo"; DB<2> $h++ and print "foo"; foo
This would work fine with the pre-increment operator:
DB<3> ++$i and print "foo"; foo
The solution suggested by swl is probably better because there is no hidden surprise in it.

As a side comment, please note that in these two code lines:

$line =~ s/\r//g; # removes windows CR characters $line =~ s/\s+$//; # removes trailing white spaces
the first line isn't useful, because the second code line will remove all trailing white spaces, including the \r Windows CR character.

Replies are listed 'Best First'.
Re^3: List comparison problem
by hippo (Bishop) on Aug 16, 2019 at 09:34 UTC
    the first line isn't useful, because the second code line will remove all trailing white spaces, including the \r Windows CR character.

    While I take your point, they are not entirely equivalent. The difference is that the first line removes all the \r characters wherever they appear in the line. The second does not do that.

    use strict; use warnings; use Test::More tests => 2; my $have = "foo\rbar\rbaz\r\n"; my $want = "foobarbaz"; $have =~ s/\s+$//; isnt $have, $want, 'Not all carriage returns removed'; $have =~ s/\r//g; is $have, $want, 'All carriage returns removed';

    I've spent far too much time over the years fighting poorly-formed, non-compliant, randomly-encoded data originating from Windows to assume anything about the quality of such data. YMMV.

      Yes, you're absolutely right, they are not entirely equivalent. ++

      But the aim of the OP code is really obviously to remove Windows CR characters from Windows line endings. And for that, that's OK.

      Having said that, I completely agree that I have also seen quite a few times poorly-formed, non-compliant, randomly-encoded data originating from Windows.

      I should also say that if my input was similar to your $have variable, I would probably have to think twice before I decided to remove CR characters within the string. It would really depend on that the final aim of the file comparison is.

      THANKS to all of you for the information. -perlmonkster