How to invoke shell in perl and how to capture the error if any?

本文介绍了在Perl中使用不同的方法来执行外部命令并获取其输出。主要讨论了使用system函数与反引号(`)的区别,并简要提及了qx运算符的用法。通过实例说明如何正确地获取wc -l命令的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[url]http://www.perlmonks.org/?node_id=57193[/url]

system("wc -l");
Will call the given command and return the return value of that command. This is usually not what you want, because most of the times wc -l will mean that you want to get the number of lines back from that call and not if that call was successful or not.


$nol = `wc -l`
The backticks call the command and return it's output into the variable (here $nol. In this case this will be what you want.
Another way of doing this is to use

$nol = qx/wc -l/;
(mnemonic: qx quote execute). I think is just the same as the backquotes (at least I don't know any difference)

Of course there are other ways (exec,fork) that behave different with respect to processes, but I don't know much about this.

And use $? to check the error code of backticks of system().
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值