简体   繁体   English

Perl核心中是否有任何东西可以自动替换“ <>”运算符?

[英]Is there anything in core Perl to auto-chomp lines from “<>” operator?

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. 在进行Perl编码时,我的一个小烦恼是必须记住切掉从输入中读取的行。 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? Perl中是否有任何编译指示,模块或其他任何东西(强烈推荐的Core模块),这些东西会自动压缩使用<>运算符读取的每一行?

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. 除了您已经提到的各种源过滤器之外,恐怕我不知道什么对您而言是“ hack”。 Do you consider any of these obviousish solutions to be “hacks”? 您是否认为这些显而易见的解决方案中的任何一种都是“骇客”?

  1. overriding *CORE::readline in the current package 在当前包中覆盖*CORE::readline
  2. overriding *CORE::GLOBAL::readline in all packages 在所有软件包中覆盖*CORE::GLOBAL::readline
  3. handle ties to a class with a custom READLINE method 使用自定义READLINE方法处理与类的联系
  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. 请注意,所有这四个解决方案只需要纯Perl,就不需要其他任何东西。 They do not even require any core modules, let alone any CPAN modules. 他们甚至不需要任何核心模块,更不用说任何CPAN模块了。

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: 我想您已经知道这一点,但是当您将命令行选项-nl组合在一起时,您将获得所需的行为(假设您需要隐式while(<>)循环:

$ 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: 通常,这两个选项用于通过bash命令行运行简短的perl命令,但我想没有什么可以阻止您在脚本中执行此操作:

#!/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 在此处对此行为的简要说明: http : //www.perlmonks.org/?node_id=324749

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM