如何将参数从 perl 脚本传递到 bash 脚本

发布于 2024-12-03 00:03:25 字数 163 浏览 0 评论 0原文

我试图在 perl 中使用 grep,但我必须从 perl 接收参数才能将它们与 grep 选项一起使用,我这样做

#!/usr/bin/perl 
system(grep -c $ARGV[0] $ARGV[1]);

会引发错误,这如何实现?

im trying to use grep in perl, but i have to recive arguments from perl to use them with grep options, im doing this

#!/usr/bin/perl 
system(grep -c $ARGV[0] $ARGV[1]);

this throws an error, how can this be implemented?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乖乖兔^ω^ 2024-12-10 00:03:25
system('grep', '-c', $ARGV[0], $ARGV[1]);

但请考虑这是否是您想要做的。 Perl 可以自己做很多事情,而不需要调用外部程序。

system('grep', '-c', $ARGV[0], $ARGV[1]);

But consider whether that's what you want to do. Perl can do a lot of things itself without invoking external programs.

数理化全能战士 2024-12-10 00:03:25

system() 的参数必须是一个字符串 (或字符串列表)。尝试:

#!/usr/bin/perl 
system("grep -c $ARGV[0] $ARGV[1]");

The argument to system() has to be a string (or list of strings). Try:

#!/usr/bin/perl 
system("grep -c $ARGV[0] $ARGV[1]");
后eg是否自 2024-12-10 00:03:25

您可能无法从该代码中得到您所期望的结果。来自perldoc -f system

The return value is the exit status of the program as returned by 
the "wait" call.  

system实际上不会为您提供来自grep的计数,而只是来自grep进程的返回值。

为了能够在 perl 中使用该值,请使用 qx() 或反引号。例如,

my $count  = `grep -c ... `;
# or
my $count2 = qx(grep -c ...);

请注意,这将在数字后给您一个换行符,例如“6\n”。

但是,为什么不全部使用perl呢?

my $search = shift;
my $count;
/$search/ and $count++ while (<>);
say "Count is $count";

不过,由菱形运算符 <> 执行的隐式 open 如果落入坏人之手,可能会很危险。您可以使用三参数打开方式手动打开文件:

use autodie;
my ($search, $file) = @ARGV;
my $count;
open my $fh, '<', $file;
/$search/ and $count++ while (<$fh>);
say "Count is $count";

You may not get what you expect from that code. From perldoc -f system:

The return value is the exit status of the program as returned by 
the "wait" call.  

system will not actually give you the count from grep, just the return value from the grep process.

To be able to use the value inside perl, use qx() or backticks. E.g.

my $count  = `grep -c ... `;
# or
my $count2 = qx(grep -c ...);

Be aware that this will give you a newline after the number, e.g. "6\n".

However, why not use all perl?

my $search = shift;
my $count;
/$search/ and $count++ while (<>);
say "Count is $count";

The implicit open performed by the diamond operator <> can be dangerous in the wrong hands, though. You can instead open the file manually with a three-argument open:

use autodie;
my ($search, $file) = @ARGV;
my $count;
open my $fh, '<', $file;
/$search/ and $count++ while (<$fh>);
say "Count is $count";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文