Can grep be used on a Perl variable?
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";
}
精彩评论