perl inside bash: How to call perl on a script saved in a string

删除回忆录丶 提交于 2019-12-02 05:21:57

问题


I need to execute the same perl script, multiple times, on different files.

To ease the process, I am trying to save the perl script as a bash string, and call perl over the string, as in the "doesn't work" part of the code below:

#!/bin/sh

# works
perl -e 'print 1;'

# doesn't work
S="'print 1;'"
perl -e $S
perl -e $S

I get the following output:

1Can't find string terminator "'" anywhere before EOF at -e line 1.
Can't find string terminator "'" anywhere before EOF at -e line 1.

What am I doing wrong here? Can I achieve the same effect in some other way?


回答1:


You simply have too many quotes in your string $S:

#!/bin/sh

# works
perl -e 'print 1;'

# also works
S='print 1;'    
perl -e "$S"

I have also added some double quotes around "$S", which prevents problems with word splitting.

Another option is to use the -x switch to Perl:

#!/bin/sh

perl -x "$0"

echo <<EOF >/dev/null
#!/usr/bin/env perl
my $a=5;
print "$a\n";
__END__
EOF

echo 'something else'

$0 is the name of the current script, so Perl looks for the first line starting with #! and containing perl and interprets everything up to __END__ as a Perl script. The echo >/dev/null prevents the Perl script from being interpreted by the shell.



来源:https://stackoverflow.com/questions/27765610/perl-inside-bash-how-to-call-perl-on-a-script-saved-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!