in reply to Re^7: Print word from text file that is not an exact match
in thread Print word from text file that is not an exact match

Try modifying the regex to

if ( my ($name) = $line =~ />(.*$search[^<]*)/ ){

poj

Replies are listed 'Best First'.
Re^9: Print word from text file that is not an exact match
by TonyNY (Beadle) on Jun 10, 2018 at 23:57 UTC
    Yes that did the trick, thanks again poj. Just noticed that this block of code works only if searching for one computer:
    # result if ($count){ print "$count matches\n"; } else { print "No matches found\n";
    It doesn't work when searching for a list of computers. If some of the computers are found the one(s) not found "No matches found" is not returned. Is there a way to print "$name - no matches found\n"; In the following block of code? Maybe something like this?
    # search text file open IN, '<',$file or die "Could not open $file : $!"; while (my $line = <IN>){ # repeat line search for each computer foreach my $search (@computers) { if ( my ($name) = $line =~ /($search[\.\w]*)/ ){ print "Name ; $name\n"; ++$count; } else if ( my ($name) = $line =~ /($search[-eq " "]*)/ ){ print "$name -- No matches found\n"; } } }
    -Tony

      Change the array @computers to a hash %computers. It is slightly more complicated as I have made %computers a HashOFArrays to allow for 1 search term to match more than 1 name.

      #!/usr/bin/perl use strict; my $count = 0; my $namefile = $ARGV[0] || 'names.txt'; # default if no argument # names.txt #ServerName1 #ServerName2 # get list of computers to search for my %computers; open FILE,'<',$namefile or die "Could not open $namefile : $!"; while (<FILE>){ chomp; s/^\s+|\s+$//g; # trim spaces next unless /\S/; # skip blank lines $computers{$_} = []; # array to hold search results } close FILE; my $file = "computernames.txt"; # computernames.txt #<Answer type="string">ServerName1.FD.net.org</Answer> #<Answer type="string">ServerName2.FD.net.org</Answer> #<Answer type="string">ServerName3.FD.net.org</Answer> #<Answer type="string">ServerName3a.FD.net.org</Answer> # search text file open IN, '<',$file or die "Could not open $file : $!"; while (my $line = <IN>){ # repeat line search for each computer foreach my $search (keys %computers) { if ( my ($name) = $line =~ />(.*$search[^<]*)/ ){ printf "Match '%-20s => %s\n",$search,$name; push @{$computers{$search}},$name; # store match } } } close IN; # result print "\nNo matches found for :\n"; for my $search (sort keys %computers){ print "$search\n" if @{$computers{$search}} == 0; } print "\nMatches found for :\n"; for my $search (sort keys %computers){ for my $name (@{$computers{$search}}){ printf "Match %-20s => %s\n",$search,$name; } }
      poj
        Thanks poj works as advertised.