tags:

views:

93

answers:

1

Is it possible one way or another to, within a Perl script, effectively execute grep against a Perl variable? An equivalent Perl function 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.

+5  A: 

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";
}
ghostdog74
As in the example, the text that I want to "grep" is already contained within a variable. So would your suggestion become `$newvar = $var =~ /foo/;` or am I misunderstanding? Also, no particular reason that I wanted to use grep other than that I am familiar with it already.
Structure
`$newvar` will contain return value of the search if `foo` is found.
ghostdog74
Fantastic, thank you. I know enough to be dangerous, but not enough to know what I am looking for. :) I can accomplish what I am looking for now.
Structure