1

我是 Perl 的新手,我正在使用 Perl 单行代码以及一些简单的 Perl 脚本来完成我的任务。

我想知道是否有可能以代码格式组合一堆单行代码并只运行包含单行代码的特定文件?例如,如果我有 3 个单行程序要逐个运行,我可以将这 3 个单行程序放在一个名为file.pl的文件中并运行它吗?

oneliner....
oneliner....

code

oneliner....

我感兴趣的所需格式如上所示。

4

3 回答 3

5

听起来你想要一个 shell 脚本,其中只有一个衬里:

 #!/bin/sh

 perl -le '...'
 perl -ane '...'
 perl -e '...'

如果你想在 Perl 程序的中间运行一个单行,你可以用system来做:

#!/usr/bin/perl

system( q( perl -le '...' ) );

但是,如果您已经在 Perl 程序中,您可以将单行代码扩展为非速记代码并将其放入程序中。例如,请参阅如何将多个 Perl 单行代码合并到一个脚本中?

于 2012-08-14T03:48:18.267 回答
0

Essentially, yes. You take the actual commands and put them in a file. So, using the example from the previous answer, create a file containing:

print reverse <>

Then run it using perl. On Unix-like machines that would be

perl file.pl

On windows I guess it will be similar. Search for "running perl scripts under windows", or similar, in google.

于 2012-08-14T01:07:34.083 回答
-1

Generally, that wouldn't work and it wouldn't make much sense. Typically, a perl oneliner calls perl with some commands and parameters. For example, here's a typical oneliner:

perl -e 'print reverse <>' foo.txt

However, if you put this in a script, you get the following:

Bareword found where operator expected at .\one.pl line 1, near "'print reverse <>' foo"
        (Missing operator before foo?)
syntax error at .\one.pl line 1, near "perl -e "
Execution of .\one.pl aborted due to compilation errors.

So, the format of script and the format of a oneliner are not compatible. However, it's usually possible to convert oneliners to script format by extracting the commands and parameters from the oneliner.

于 2012-08-14T01:02:02.587 回答