Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell 如何格式化perl oneliner?_Shell_Perl - Fatal编程技术网

Shell 如何格式化perl oneliner?

Shell 如何格式化perl oneliner?,shell,perl,Shell,Perl,如果我有一个perl单行程序从命令行运行它:例如 perl -MData::Dumper -MJSON=decode_json -e 'my @array = @{decode_json($data)}; foreach my $i (@array) { etc }' 如何设置格式,使其更具可读性,即添加新行?如果我这样做: 妈 当我添加像这样的新行来格式化代码时,命令会中断写一个实际的perl脚本 #!/usr/bin/env perl use strict; use warnings;

如果我有一个perl单行程序从命令行运行它:例如

perl -MData::Dumper -MJSON=decode_json -e 'my @array = @{decode_json($data)}; foreach my $i (@array) { etc }'
如何设置格式,使其更具可读性,即添加新行?如果我这样做:


当我添加像这样的新行来格式化代码时,命令会中断

写一个实际的perl脚本

#!/usr/bin/env perl
use strict;
use warnings; 

use JSON qw ( decode_json );

my $json = decode_json ( do{ local $/; <> } ); #read from stdin/file specified on command line

foreach my $element ( @$json ) { #iterate
   # do things
}

但说真的——如果你想让一行代码更具可读性,那么答案是‘把它写成脚本,这就是它们的目的’

这很有趣:您想要一行,为了可读性,应该跨越多行。这听起来像是一个矛盾

您所能做的就是放下
-e
开关,制作一个HERE文档:

perl -MData::Dumper -MJSON=decode_json <<ENDOFPERL
  # Your multi-line one-liner goes here
ENDOFPERL

perl-MData::Dumper-MJSON=decode_json正如其他人已经说过的,如果您的一行代码太复杂,无法容纳一行代码,那么应该使用脚本

在一些罕见的情况下(当脚本调试并运行时),您可以将perl脚本内联到
bash
脚本中,如下所示:

#!/bin/bash

# bash function which prints the perl script
perlcode() {
cat - <<'PERLCODE'
use scrict;
use warnings;
# ... rest of your script
PERLCODE
}

#and use the inlined script as    
perl <(perlcode)
e、 g.与perl/path/to/script
完全相同。这样的内联perl脚本与普通perl脚本一样工作,例如可以包含
\uuuu DATA\uuuu
部分


你必须使用引号中的
,你可能想知道为什么它们被称为单行程序…也许你应该编写一个真正的Perl脚本,并将它保存在一个可执行文件中,如果它足够复杂,你不想让它出现在一行中…它可以。Perl可以在脚本文件中编写,然后可以使用
perltidy
之类的东西使其格式一致,还可以使用手写变量名、换行等等。我认为单行程序是讨厌的野兽,不应该成为生产代码的一部分。绝对是这样。一行程序应该是一次性的。例如,扔掉代码。如果你需要保留它,它应该是一个脚本。听起来很有趣。如果我有其他选项,例如
-n
?我不明白为什么会出现问题,例如
perl-nlp input_data.txt,但是如果在
-e'
之后在命令行按enter键,它会中断您使用的平台是什么?在我身上可以吗?
#!/bin/bash

# bash function which prints the perl script
perlcode() {
cat - <<'PERLCODE'
use scrict;
use warnings;
# ... rest of your script
PERLCODE
}

#and use the inlined script as    
perl <(perlcode)
perl /dev/fd/63 #some temporary file descriptor