从文件中读取并将内容与变量进行比较
#!/usr/bin/perl
some code........
..................
system ("rpm -q iptables > /tmp/checkIptables");
my $iptables = open FH, "/tmp/checkIptables";
上面的代码检查您的 Linux 机器上是否安装了 iptables
?如果已安装,命令rpm -q iptables
将给出如下所示的输出:
iptables-1.4.7-3.el6.x86_64
现在我已将此输出重定向到名为checkIptables
的文件。
现在我想检查变量 $iptables
是否与上面给出的输出匹配。我不关心版本号。
它应该类似于
if ($iptables eq iptables*){
...............
.......................}
But iptables* 给出错误。
#!/usr/bin/perl
some code........
..................
system ("rpm -q iptables > /tmp/checkIptables");
my $iptables = open FH, "/tmp/checkIptables";
The above code checks whether iptables
is installed in your Linux machine? If it is installed the command rpm -q iptables
will give the output as shown below:
iptables-1.4.7-3.el6.x86_64
Now I have redirected this output to the file named as checkIptables
.
Now I want to check whether the variable $iptables
matches with the output given above or not. I do not care about version numbers.
It should be something like
if ($iptables eq iptables*){
...............
.......................}
But iptables* gives error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用正则表达式来检查字符串:
此外,您不需要 tmp 文件,您可以打开一个管道:
这将读取输出的第一行,并根据正则表达式进行检查。
或者您可以使用反引号:
请注意,反引号可能会返回多行数据,因此您可能需要对此进行补偿。
You could use a regex to check the string:
Also, you do not need a tmp file, you can instead open a pipe:
This will read the first line of the output, and check it against the regex.
Or you can use backticks:
Note that backticks may return more than one line of data, so you may need to compensate for that.
我认为您正在寻找的是正则表达式或“模式匹配”。您希望字符串匹配一个模式,而不是特定的事物。
=~
是绑定 运算符,它告诉提供的正则表达式其源是该变量。正则表达式只是表示在字符串的开头查找序列“iptables”,后跟“word-break”。由于“-”是“非单词”字符(不是字母数字或“_”),因此它会破坏单词。您也可以使用“-”:但是您可能可以使用此语句完成整个操作:
通过反引号将输出直接传递到列表中,并通过
any
搜索该列表(请参阅List::MoreUtils::any
I think what you're looking for is a regular expression or a "pattern match". You want the string to match a pattern, not a particular thing.
=~
is the binding operator and tells the supplied regular expression that its source is that variable. The regular expression simply says look at the beginning of the string for the sequence "iptables" followed by a "word-break". Since '-' is a "non-word" character (not alphanumeric or '_') it breaks the word. You could use '-' as well:But you can probably do the whole thing with this statement:
piping the output directly into a list via backticks and searching through that list via
any
(SeeList::MoreUtils::any
为什么不直接看“rpm -q”的返回值,无论安装与否,它都会分别返回0或1?
Why not just look at the return value of "rpm -q", which will return 0 or 1 whether it is installed or not respectively?