开发者

Can grep be used on a Perl variable?

开发者 https://www.devze.com 2022-12-22 01:16 出处:网络
Is it possible one way or another to, within a Perl script, effectively execute grep against a Perl variable? An equivalent Perl fu开发者_C百科nction would be equally acceptable, I just want to keep t

Is it possible one way or another to, within a Perl script, effectively execute grep against a Perl variable? An equivalent Perl fu开发者_C百科nction would be equally acceptable, I just want to keep the solution as simple as possible.

For example:

#!/usr/bin/perl
#!/bin/grep

$var="foobar";

$newvar="system('grep -o "foo" $var');

sprintf $newvar;

Where I expect sprintf $newvar to output foo.

Would also welcome any feedback on best practice here. I am not extremely familiar with Perl.


you can just use regex matching in Perl. No need to call external "grep" command.

$var =~ /foo/;

please read documentation perlrequick for introduction on how to search for patterns in variables. Also of interest is Perl's own grep.

$var="foobar";
if ( $var =~ /foo/){
  print "found foo\n";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号