2016-07-25 10 views
-1

Ich suche nach einer Liste von Stichwörtern aus einer Datei. Ich bin in der Lage, das ganze Schlüsselwort zu finden, aber für einige Schlüsselwörter muss ich einen ersten Teil des Wortes zusammenbringen. Für das BeispielPerl Suche mehrere Schlüsselwort mit Regex

DES 
AES 
https:// --- here it should match the word starting with https:// but my code considers the whole word and skips it. 

Zum Beispiel des oben genannten Keywords sollte ich aus dem unten Eingang nur DES, DES und https:// zum Spiel:

DES some more words 
DESTINY and more... 
https://example.domain.com 
http://anotherexample.domain.com # note that this line begins with http://, not https:// 

Hier ist, was ich bisher versucht habe:

use warnings; 
use strict; 

open STDOUT, '>>', "my_stdout_file.txt"; 
#die qq[Usage: perl $0 <keyword-file> <search-file> <file-name>\n] unless @ARGV == 3; 

my $filename = $ARGV[2]; 
chomp ($filename); 
open my $fh, q[<], shift or die $!; --- This file handle Opening all the 3 arguments. I need to Open only 2. 

my %keyword = map { chomp; $_ => 1 } <$fh>; 
print "$fh\n"; 
while (<>) { 
    chomp; 
    my @words = split; 
    for (my $i = 0; $i <= $#words; $i++) { 
      if ($keyword{^$words[ $i ] }) { 
        print "Keyword Found for file:$filename\n"; 
        printf qq[$filename Line: %4d\tWord position: %4d\tKeyword: %s\n], 
          $., $i, $words[ $i ]; 
      } 
    } 
} 
close ($fh); 
+0

Wie kann das Programm wissen, ob Sie ein vollständiges Wort Spiel wollen oder nur ein Teilmatch? – Borodin

Antwort

0

Hier ist eine funktionierende Lösung für das, was ich denke, Sie versuchen zu erreichen. Lassen Sie mich wissen, wenn nicht:

use warnings; 
use strict; 
use feature qw/ say /; 

my %keywords; 

while(<DATA>){ 
    chomp; 
    my ($key) = split; 
    my $length = length($key); 
    $keywords{$key} = $length; 
} 

open my $in, '<', 'in.txt' or die $!; 


while(<$in>){ 
    chomp; 
    my $firstword = (split)[0]; 

     for my $key (keys %keywords){ 
      if ($firstword =~ m/$key/){ 
       my $word = substr($firstword, 0, $keywords{$key}); 
       say $word; 
      } 
     } 
} 
__DATA__ 
Keywords:- 
DES 
AES 
https:// - here it should match the word starting with https:// but my code considers the whole word and skipping it. 

Für eine Eingabedatei enthält:

here are some words over multiple 
lines 
that may or 
may not match your keywords: 
DES DEA AES SSE 
FOO https: 
https://example.domain.com 

Diese Der Ausgang gibt:

DES 
https:// 
+0

Ich erhalte Fehler beim Ausführen des Codes. ** Verwendung des nicht initialisierten Werts in der Musterübereinstimmung (m //) ** – John

+0

@John - Haben Sie es geschafft, dieses Problem zu lösen? – fugu

+0

Ja, ich tat es. Vielen Dank – John