Perl: Find a line in a txt by matching typed words?

Asked

Viewed 141 times

5

Good afternoon,

I have a notepad with several lines typed as for example:

★ Bayonet
★ Bayonet | Autotronic (Battle-Scarred)
★ Bayonet | Blue Steel (Minimal Wear)
★ Bayonet | Case Hardened (Battle-Scarred)
★ Bayonet | Case Hardened (Factory New)
★ Bayonet | Case Hardened (Field-Tested)

In my code one of the lines will wait for the keyboard input asking what name you want to find

use strict;
open(FILEHANDLE,'<','filtradas.txt') or die "Arquivo não pode ser aberto\n";
my @linhas = <FILEHANDLE>;
close(FILEHANDLE);
print "Informe o nome do item que deseja encontrar: ";
my $nome = <STDIN>; chomp($nome);
foreach my $linhas(@linhas) {
chomp($linhas);
if($linhas =~ m/$nome/gi) {
    print $linhas."\n";
}
}

The question is : Is there any way to create a regex that if for example I type in the keyboard input "Bayonet Case" it print me all the results of the notepad that contains Bayonet + Case in the same line? In the case:

★ Bayonet | Case Hardened (Battle-Scarred)
★ Bayonet | Case Hardened (Factory New)
★ Bayonet | Case Hardened (Field-Tested)

I’m sorry if I couldn’t be clear, in case you didn’t understand I try to explain otherwise.

Thank you in advance.

1 answer

1


Problem solved with the following function :

$nome =~ s/\s+/.*/g;

what turns "Bayonet case" into ( "Bayonet. *case". ).

Thank you Hernan.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.