简体   繁体   English

如何将Perl脚本转换为单行

[英]How can I convert Perl script into one-liner

I know of Perl compiler back-end that allows you to convert any one-liner into script on following matter: 我知道Perl编译器后端,它允许您在以下情况下将任何一种代码转换为脚本:

perl -MO=Deparse -pe 's/(\d+)/localtime($1)/e'

Which would give the following output 这将给出以下输出

LINE: while (defined($_ = <ARGV>)) {
s/(\d+)/localtime($1);/e;
}
continue {
    print $_;
}

Is there possibly a reverse tool, usable from command-line, which provided full script will generate one-liner version of it? 是否可能有一个可从命令行使用的反向工具,提供完整脚本将生成此工具的单行版本?

Note: The above example was taken from https://stackoverflow.com/a/2822721/4313369 . 注意:上面的示例来自https://stackoverflow.com/a/2822721/4313369

Perl is a free-form syntax language with clear statement and block separators, so there is nothing preventing you from simply folding a normal script up into a single line. Perl是一种自由形式的语法语言,具有清晰的语句和块分隔符,因此没有什么可以阻止您将普通脚本简单地折叠成一行。

To use your example in reverse, you could write it as: 要反向使用示例,可​​以将其编写为:

$ perl -e 'LINE: while (defined($_ = <ARGV>)) { s/(\d+)/localtime($1);/e; } continue { print $_; }'

This is a rather contrived example, since there is a shorter and clearer way to write it. 这是一个非常人为的示例,因为有一种更短,更清晰的编写方式。 Presumably you're starting with scripts that are already as short and clear as they should be. 大概您是从已经足够短而清晰的脚本开始的。

Any use statements in your program can be turned into -M flags. 程序中的所有use语句都可以变成-M标志。

Obviously you have to be careful about quoting and other characters that are special to the shell. 显然,您必须谨慎对待引号和其他Shell特有的字符。 You mention running this on a remote system, by which I assume you mean SSH, which means you now have two levels of shell to sneak any escaping through. 您提到在远程系统上运行此程序,我假设您的意思是SSH,这意味着您现在拥有两个级别的Shell,可以进行任何转义。 It can be tricky to work out the proper sequence of escapes, but it's always doable. 确定正确的转义序列可能很棘手,但始终可行。

This method may work for automatically translating a Perl script on disk into a one-liner: 此方法可以自动将磁盘上的Perl脚本转换为单行代码:

$ perl -e "$(tr '\n' ' ' < myscript.pl)"

The Perl script can't have comments in it, since that would comment out the entire rest of the script. Perl脚本中不能包含注释,因为这会注释掉脚本的其余部分。 If that's a problem, a bit of egrep -v '\\w+#' type hackery could solve the problem. 如果这是一个问题,则可以使用一些egrep -v '\\w+#'类型的hackery解决此问题。

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

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