John
John

Reputation: 11

how to pass arguments from perl script to bash script

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?

Upvotes: 1

Views: 1972

Answers (3)

TLP
TLP

Reputation: 67900

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";

Upvotes: 0

user554546
user554546

Reputation:

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

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

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263257

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.

Upvotes: 7

Related Questions