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?
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.
The argument to system() has to be a string (or list of strings). Try:
#!/usr/bin/perl
system("grep -c $ARGV[0] $ARGV[1]");
'; 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 systemscript.pl "Can't" fileYou 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";
alias grepc='grep -c $@'in.bashrc