deviks
deviks

Reputation: 25

Very Strange Bug When Printing in Perl

So here's the snippet of code that's running:

    if($verbose){
            my $toPrint = "Added ";
            if($types[$count]){
                    $toPrint .= "$types[$count] ";
                    print "Type: $types[$count]\n"; #Manual debugging
                    print "\$toPrint: $toPrint\n"; #Manual debugging
            }
            if($addressTypes[$count]){
                    $toPrint .= "$addressTypes[$count] ";
                    print "Address Type: $addressTypes[$count]\n"; #Manual debugging
                    print "\$toPrint: $toPrint\n"; #Manual debugging
            }
            if($addresses[$count]){
                    $toPrint .= "$addresses[$count] ";
                    print "Address: $addresses[$count]\n"; #Manual Debugging
                    print "\$toPrint: $toPrint\n"; #Manual debugging
            }
            $toPrint .= "to the address entries\n";
            print "Final value of \$toPrint before printing: $toPrint\n"; #Manual debugging
            print $toPrint;
    }

We're inside a for loop, with $count being the variable we're iterating on. Here's what the output of a particular runthrough of this code looks like. For the sake of privacy, I've replaced the IP in it with ###.###.###.###.

    Type: zix01
    $toPrint: Added zix01
    Address Type: A
    $toPrint: Added zix01 A
    Address: ###.###.###.###
     toPrint: Added zix01 A ###.###.###.###
     to the address entries before printing: Added zix01 A ###.###.###.###

     to the address entries#.###

As you can see, there are several things wrong with this.

  1. The line after the line starting with "Address" starts with a space instead of the intended $.
  2. The line after that starts with " to the address entries" instead of "Final value of $toPrint".
  3. That line also does not have " to the address entries" at the end of it.
  4. There is an extra line break between the last two lines.
  5. The last line does not contain the word "Added zix01 A" even though the variable it's supposed to be printing does.
  6. The last line also does not include the IP it is supposed to be printing, except for the last 5 characters of it, which are coming out after the rest of the string but before the line break.

Does anyone have any idea what's going on here?

edited for grammar.

Upvotes: 2

Views: 459

Answers (1)

mob
mob

Reputation: 118605

Are there carriage return characters (\r) somewhere in your output? On Unix use perl script.pl | od -c to examine each character of output.

Files generated in Windows often have \r\n line endings. When those files are read in a Unix environment, chomp will only remove the \n. When I have to worry about portability, I usually skip chomp and just say s/\s+$// on the input (or s/[\r\n]+$// if you don't want to strip all the trailing whitespace).

Upvotes: 5

Related Questions