Question

#!/usr/bin/perl
use warnings;
use Switch;

while (<>) {
  next if /^\s*\/\//;
  next if /^\s*$/;
  my $line="$_";
  chomp($line);
  print $line;
  print "Checking for line:\n$line";
}

This is my code which takes input file from command line. It takes the following file as input:

// Computes R0 = 2 + 3

@2
D=A
@3
D=D+A
@0
M=D

In the code I tried to remove the newline at the end of each line with the help of chomp function. But when I try to print the line after application of chomp it prints nothing for that line. It gives the following output:

Checking for line:
Checking for line:
Checking for line:
Checking for line:
Checking for line:
Checking for line:

Why is the line not being printed?

Was it helpful?

Solution

I can reproduce your problem if the input has \r\n line endings. chomp will remove the \n but leave the \r, which (on Unix) will have the effect of moving the cursor to the beginning of the line (without advancing to the next line). Since your lines are short, the next output (Checking for line) completely overwrites it.


Sorry, Borodin. so the solutions are:

  1. don't create input files for your Unix Perl scripts on Windows, or if you must
  2. use something stronger than chomp. I always like to use

    $line =~ s/\s+$//;
    

    so long as you don't need to preserve trailing spaces

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top