See sample code below

> 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
>
>
>
> out.txt
> ------
>
> fc3/2  10:00:00:00  host1
> fc3/23 10:00:00:00  host2
> fc10/1 10:00:00:00  host3
> fc10/11 10:00:00:00  host4
> fc3/1 10:00:00:00  host5
> fc3/14 10:00:00:00  host6
> fc12/1 10:00:00:00  host7
> fc12/12    10:00:00:00  host8
>
>
> sample code
> -----------------
>
> my @check = (fc3/23, fc10/1, fc3/14, fc12/12);
>
> my $f2 = 'out.txt';
> for my $element(@check) {
> open my $fh2, '<', $f2 or die "could not open $f2: $!";
> while (my $line = <$fh2>) {
> chomp $line;
> if ($line = / ^(fc\d+\/\d+/) {
> $match=$&;
> }
> if  ($element =~ $match) {
> print "$line \n";
> }
> }
> }
>
>
> required output
> --------------------
>
> fc3/23 10:00:0:00  host2
> fc10/1 10:00:0:00  host3
> fc3/14 10:00:00:00  host6
> fc12/12    10:00:00:00  host8
>
> Thanks
> Sj
>

This worked for me:

#!/usr/bin/perl

  use strict;          # Always a good idea!
  use warnings;        # likewise!

  # You need quotes around your literals in the line that creates
  # and assigns @check:
  my @check = ("fc3/23", "fc10/1", "fc3/14", "fc12/12");
  my $f2 = 'out.txt';

  # The following lines create a reqexp variable that will match any
  # of the strings in @check.  Note in the map that I placed a space
  # after "$_".  This takes care of the problem where "fc3/2" matched
  # "fc3/23".  When this is done, for this sample, the generated regular
  # expression looks like:
  #    (?:fc3/23 )|(?:fc10/1 )|(?:fc3/14 )|(?:fc12/12 )
  # This attempts to match against all of the strings that were in
@check.
  # The use of "(?:" instead of "(" to start each group will make the
  # parenthesis "non-capturing", which is a bit quicker when you don't
need
  # to capture the actual matches.
  #

  my @tmpcheck = map {"(?:$_ )"} @check;
  my $regexp_str = join "|", @tmpcheck;
  my $regexp = qr/$regexp_str/;

  open my $fh2, '<', $f2 or die "could not open $f2: $!";

  while (my $line = <$fh2>) {
    print "$line" if $line =~ $regexp;    # Print only lines that match
  }

  # Note that I did not chomp the newline and put it back on when
printing.
  # The presence of the newline does not effect the match in this
case, so
  # that was not necessary.

Best of luck.

Nathan
-- 



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