1

im trying to use grep in perl, but i have to recive arguments from perl to use them with grep options, im doing this

#!/usr/bin/perl 
system(grep -c $ARGV[0] $ARGV[1]);

this throws an error, how can this be implemented?

1
  • 1
    alias grepc='grep -c $@' in .bashrc Commented Sep 6, 2011 at 17:59

3 Answers 3

7
system('grep', '-c', $ARGV[0], $ARGV[1]);

But consider whether that's what you want to do. Perl can do a lot of things itself without invoking external programs.

Sign up to request clarification or add additional context in comments.

1 Comment

0

The argument to system() has to be a string (or list of strings). Try:

#!/usr/bin/perl 
system("grep -c $ARGV[0] $ARGV[1]");

2 Comments

The list form is safer. Consider the possibility that someone invoked your script with a first argument of '; rm -rf $HOME'. That's not really an issue unless the script runs with additional privileges (the user could have run rm -rf $HOME directly), but it's worth thinking about. The single-string form is useful if you need to invoke the shell to execute the command for you; for example, system("command1 | command2") can be done in Perl, but it's a lot of work. perldoc -f system
It also fails for simpler stuff like script.pl "Can't" file
0

You may not get what you expect from that code. From perldoc -f system:

The return value is the exit status of the program as returned by 
the "wait" call.  

system will not actually give you the count from grep, just the return value from the grep process.

To be able to use the value inside perl, use qx() or backticks. E.g.

my $count  = `grep -c ... `;
# or
my $count2 = qx(grep -c ...);

Be aware that this will give you a newline after the number, e.g. "6\n".

However, why not use all perl?

my $search = shift;
my $count;
/$search/ and $count++ while (<>);
say "Count is $count";

The implicit open performed by the diamond operator <> can be dangerous in the wrong hands, though. You can instead open the file manually with a three-argument open:

use autodie;
my ($search, $file) = @ARGV;
my $count;
open my $fh, '<', $file;
/$search/ and $count++ while (<$fh>);
say "Count is $count";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.