在bash的定界符Perl脚本 [英] Perl script in bash's HereDoc

查看:148
本文介绍了在bash的定界符Perl脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的有些的在bash脚本定界符写一个Perl脚本?

Is possible somewhat write a perl script in a bash script as heredoc?

这不工作(例如只)

#/bin/bash
perl <<EOF
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF

这里是一些不错的方式如何嵌入一个Perl脚本到bash脚本?想从一个bash脚本运行Perl脚本,不想把它放到外部文件中。

Is here some nice way how to embed a perl script into a bash script? Want run perl script from an bash script and don't want put it into external file.

推荐答案

这里的问题是,脚本被传递到perl标准输入,所以试图处理标准输入从脚本不起作用。

The problem here is that the script is being passed to perl on stdin, so trying to process stdin from the script doesn't work.

perl -e '
while(<>) {
    chomp;
    print "xxx: $_\n";
}
'

使用字符串字面量是最直接的方式来写这篇文章,虽然它如果Perl脚本包含单引号本身的效果并不理想。

Using a string literal is the most direct way to write this, though it's not ideal if the Perl script contains single quotes itself.

#/bin/bash

script=$(cat <<'EOF'
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF
)
perl -e "$script"

如果您通过使用脚本到perl 的perl -e ,那么你将不会有标准输入问题,你可以使用你的脚本喜欢的任何字符。这是一个有点迂回要做到这一点,虽然。 here文档生成标准输入的输入,我们需要的字符串。该怎么办?哦,我知道!这就要求 $(猫&LT;&LT; HEREDOC)。

If you pass the script to perl using perl -e then you won't have the stdin problem and you can use any characters you like in the script. It's a bit roundabout to do this, though. Heredocs yield input on stdin and we need strings. What to do? Oh, I know! This calls for $(cat <<HEREDOC).

请务必使用&LT;&LT;'EOF'而不仅仅是&LT;&LT; EOF 保持庆典从做定界符内的变量插值。

Make sure to use <<'EOF' rather than just <<EOF to keep bash from doing variable interpolation inside the heredoc.

您也可以这样写这个没有 $脚本变量,虽然它现在变得非常毛茸茸的!

You could also write this without the $script variable, although it's getting awfully hairy now!

perl -e "$(cat <<'EOF'
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF
)"

3。进程替换

perl <(cat <<'EOF'
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF
)

沿#2线,你可以使用一个叫做进程替换一个bash功能,它可以让你写≤(CMD)代替文件名。如果你使用这个,你不需要 -e ,因为你现在的perl传递一个文件名,而不是一个字符串。

Along the lines of #2, you can use a bash feature called process substitution which lets you write <(cmd) in place of a file name. If you use this you don't need the -e since you're now passing perl a file name rather than a string.

这篇关于在bash的定界符Perl脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆