Perl chomp plus =~s Yielding very strange results

122 Views Asked by At

I am writing a perl program which creates a procmailrc text file.

The output procmail requires looks like this: (partial IP addresses separated by "|")

\(\[54\.245\.|\(\[54\.252\.|\(\[60\.177\.|

Here is my perl script:

open (DEAD, "$dead");
@dead = <DEAD>;
foreach $line (@dead) { chomp $line; $line =~s /\./\\./g;
print FILE "\\(\\[$line\|\n"; }
close (DEAD);

Here is the output I am getting:

|(\[54\.245\.
|(\[54\.252\.
|(\[60\.177\.

Why is chomp not removing the line breaks? Stranger still, why is the '|' appearing at the front of each line, rather than at the end?

If I replace $line with a word, (print FILE "\(\[test\|"; }) The output looks the way I would expect it to look:

\(\[test|\(\[test|\(\[test|\(\[test|

What am I missing here?

So I found a work-around that does not use chomp: The answer was here:https://www.perlmonks.org/?node_id=504626

My new code:

open (DEAD, "$dead");
@dead = <DEAD>;
foreach $line (@junk) { 
$line =~ s/\r[\n]*//gm; $line =~ s/\./\\./g;  $line =~ s/\:/\\:/g;
print FILE "\\(\\[$line \|"; }
close (DEAD);

Thanks to those of you who gave me some hints.

1

There are 1 best solutions below

0
ikegami On

chomp removes the value of $/, which is set to the string produced by "\n" by default.

For input, however, you have

@dead = (
   "54.245\.\r\n",
   "54.252\.\r\n",
   "60.177\.\r\n",
);

This simple fix:

open(my $dead_fh, '<', $dead_qfn)
   or die("Can't open \"$dead_qfn: $!\n");

while (my $line = <$dead_fh>) {
   $line =~ s/\s+\z//;
   $line =~ s/\./\\./g
   print($out_fh "\\(\\[$line\|");
}

print($out_fh "\n");

(The alternative is to add the :crlf layer to your input handle.)

Using quotemeta makes more sense

open(my $dead_fh, '<', $dead_qfn)
   or die("Can't open \"$dead_qfn: $!\n");

while (my $line = <$dead_fh>) {
   $line =~ s/\s+\z//;
   print($out_fh quotemeta("([$line|"));
}

print($out_fh "\n");