On Fri, 23 Aug 2013 17:06:41 +0100
jet speed <speedj...@googlemail.com> wrote:

> Chaps,
> 
> Please i need help on the regular expression, i have the sample code
> below. I only want to match the entries from the array to the file
> and print the matching line
> 
> for example if i only want to match fc3/23, in my code it prints both
> the lines fc3/2 and fc3/23. How to restrict to exact matches and
> print only ex: fc3/23

[...]
> if ($line = / ^(fc\d+\/\d+/) {

First off, you mean =~ to match against a regex - that's a fairly
meaningless assignment there.  Was that a typo or is that how it
actually is in your code?

Secondly, that regex shouldn't even compile - you've missed a closing
parenthesis.

Perl should have told you something like:

  Unmatched ( in regex; marked by  ....

You meant:

if ($line =~ /^(fc\d+\/\d+)/) {

Although I would write that a little more clearly - using qr lets you
pick delimiters that avoid you having to escape the slash in the
middle, and using the "x" modifier makes the regex whitespace
insensitive, so you can space things out for readability - and also,
assign the match to a meaningful var immediately:

if (my ($port) = $line =~ qr{^ (fc \d+ / \d+ ) }x) {
    # matched, $port contains e.g. fc3/23
}


Also, iterating through the file once for each port you want to look
for is a rather inefficient approach - reverse the logic, and loop
through each line in the file, checking it against each of your ports
of interest within the loop - for example:

open my $fh, '<', $filename or die "Failed to open $filename - $!";
while (my $line = <$fh>) {
    chomp $line;
    if (my ($port) = $line =~ qr{^ (fc \d+ / \d+ ) }x) {
        if (grep { $port eq $_ } @check) {
            # $port matched one of the ones you wanted.
            print "$line\n";
        }
    }
}


Hope that helps?


-- 
David Precious ("bigpresh") <dav...@preshweb.co.uk>
http://www.preshweb.co.uk/     www.preshweb.co.uk/twitter
www.preshweb.co.uk/linkedin    www.preshweb.co.uk/facebook
www.preshweb.co.uk/cpan        www.preshweb.co.uk/github



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to