1

my below code is very simple... all im doing is grepping a file using an IP address REGEX, and any IP addresses that are found that match my REGEX, I want to store them in @array2.

i know my REGEX works, because ive tested it on a linux command line and it works exactly how I want, but when its integrated into the script, it just returns blank. there should be 700 IP's stored in the array.

#!/usr/bin/perl
use warnings;
use strict;

my @array2 = `grep -Eo "\"\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\"" test1.txt`;
print @array2;
2
  • What output do you get from printing @array2? Commented Aug 27, 2014 at 20:15
  • 4
    I would say newbies don't mix perl and shell as it doesn't work for them, and experienced ones simply know better. Commented Aug 27, 2014 at 20:16

4 Answers 4

3

Backticks `` behave like a double quoted string by default.

Therefore you need to escape your backslashes:

my @array2 = `grep -Eo "\\"\\b[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\"" test1.txt`;

Alternatively, you can use a single quoted version of qx to avoid any interpolation:

my @array2 = qx'grep -Eo "\"\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\"" test1.txt';

However, the method I'd recommend is to not shell out at all, but instead do this logic in perl:

my @array2 = do {
    open my $fh, '<', 'test1.txt' or die "Can't open file: $!";
    grep /\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b/, <$fh>;
};
Sign up to request clarification or add additional context in comments.

Comments

2

I really wouldn't mix bash and perl. It's just asking for pain. Perl can do it all natively.

Something like:

open (my $input_fh, "<", "test.txt" ) or die $!;
my @results = grep ( /\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/, <$input_fh> );

This does however, require slurping the file into memory, which isn't optimal - I'd generally use a while loop, instead.

Comments

1

The text inside the backticks undergoes double-quotish substitution. You will need to double your backslashes.

Running grep from inside Perl is dubious, anyway; just slurp in the text file and use Perl to find the matches.

1 Comment

Perl does have a grep builtin, which'll do the trick. I'd tend to use a while loop instead though, because it's less memory expensive.
0

The easiest way to retrieve the output from an external command is to use open():

open(FH, 'grep -Eo \"\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\" test1.txt'."|")  
my @array2=<FH>;
close (FH);

..though I think Sobrique's idea is the best answer here.

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.