Help with a perl subroutine regex

Hi,

I can't get this script ot work and I wa wondering if anyone could help?

I need to open a file and use a subroutine to search each line for a regular expression. If it matches then I need to return a match from the subroutine and print the result?

Any help would be greatly appreciated. I know it is simple but I can't seem to figure it out for some reason.

Thanks,
JD

#!/usr/bin/perl -w
#
#
$filename = "data.txt";

open FILE, $filename or die("could not open $filename for reading: $!");

foreach my $line (<FILE>) {

my $matched_line = &find_match($line);

if ($matched_line) {

  print "$matched_line\\n";

}

}

close FILE;

sub find_match {
$grep = @_;
if ($grep =~ m/blue/){
return $grep;
}

}
#}
#}

In the script print each of the variables line after line to see what happens.

........

Sorry, not right

I can get it to work with this:

sub find_match {
$grep = $_[0];
if ($grep =~ m/blue/){
return $grep;
}

can't exactly say why previous doesn't work, can someone chime in?

here you have assigned a list to a scalar:

$grep = @_;

the scalar will equal the length of the list instead of the value of any of the list elements. Using $_[0] properly assigns the value of a scalar to a scalar.

Ahh, thanks.

This is also wrong:

foreach my $line (<FILE>) {

to properly loop through a file you use "while":

while (my $line = <FILE>) {

the use of a subroutine in your code is also a case of over engineering. The regexp matching could just be done inside the loop.

#!/usr/bin/perl

use strict;
use warnings;

my $filename = 'data.txt';
open FILE, $filename or die "could not open $filename for reading: $!";
while (my $line (<FILE>) {
   print $line if ($line =~ m/blue/);
}
close FILE;

Thanks Everyone!

This worked for me

Any idea how I would accomlish the following;

i need a regex that will poplate $first with the first word and then $second with the second word after a space. How can i then return the two variables?

Any help would be greatly appreciated. Been trying to do this all day.

Do you want to report the first word and the second word with space in the middle?

Or first word and then a second word that follows a space?

I'm sure you can find a few ways to do this, as evident in this thread (while, foreach...)