Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything in core Perl to auto-chomp lines from "<>" operator?

Tags:

input

perl

One of the minor annoyances I have when doing Perl coding is the necessity to remember to chomp a line that you read from input. Yeah, after years of coding it's nearly automatic to remember to do so, but STILL annoying.

Is there any pragma, module or anything else in Perl (strongly preferred Core modules) that automatically chomps every line read using a <> operator?

like image 204
DVK Avatar asked Apr 14 '12 15:04

DVK


2 Answers

Beyond the asquerous source filters that you already mentioned, I’m afraid I don’t know what counts as “a hack” for your purposes here. Do you consider any of these obviousish solutions to be “hacks”?

  1. overriding *CORE::readline in the current package
  2. overriding *CORE::GLOBAL::readline in all packages
  3. handle ties to a class with a custom READLINE method
  4. operator overloading of the <> operator

Have you tried those yet?

Of those, I would think the first, or possibly the second, to be the most likely to do what you want with the least amount of fuss.

Note that all four of those solutions require nothing but pure Perl and nothing else. They do not even require any core modules, let alone any CPAN modules.

like image 196
tchrist Avatar answered Nov 04 '22 12:11

tchrist


I suppose you already know this, but when you combine the command line options -nl together you get the behavior you want (assuming you want the implicit while(<>) loop:

$ perl -nle 'printf q{%s}, $_'

Usually the two options are used to run a short perl command via bash command line, but I guess nothing prevents you from doing it in a script:

#!/usr/bin/perl -nl

# puts the newline back on if you use print:
# print

# does not put the newline back on
printf '%s', $_;

Brief description of this behavior here: http://www.perlmonks.org/?node_id=324749

like image 2
Kevin Avatar answered Nov 04 '22 12:11

Kevin