How to mimic -l inside script

perl

Solution

No. You can get the automatic appending of `"\n"` by using `$\`, but you have to add the chomp yourself.

Here's how `-l` works.

$ perl -MO=Deparse -ne 'print $_'
LINE: while (defined($_ = <ARGV>)) {
    print $_;
}

$ perl -MO=Deparse -lne 'print $_'
BEGIN { $/ = "\n"; $\ = "\n"; }      # -l added this line
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;                        # -l added this line
    print $_;
}

(The comments are mine.) Notice that `-l` added a literal `chomp $_` at the beginning of the loop generated by `-n` (and it only does that if you use `-n` or `-p`). There's no variable you can set to mimic that behaviour.

It's a little-known fact that `-l`, `-n`, and `-p` work by wrapping boilerplate text around the code you supply before it's compiled.

Problem

Is there a simple way to mimic the effect of the `-l` command-line switch within `perl` scripts? (Of course, I can always `chomp` each line and then append "\n" to each line I print, but the point is to avoid having to do this.)

Original source