Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Partial Pattern Matching

Status
Not open for further replies.

usheikh

Programmer
May 16, 2005
25
GB
I am trying to write a script that will allow me to do the following:

Consider a file called NUMBERS containing entries such as:

123456
123444
123476
345678
345677

The script when run will prompt the user to enter a number. Then it will look in NUMBERS file and display any numbers that contain the same numbers. For example, if the user entered 123, then the following numbers will be displayed to the screen:

123456
123444
123476

Is there a function or operator that will allow me to match in this way? Or any useful threads with anything similar would be much appreciated. Thanks.
 
This should work. Enjoy!

Code:
#!/usr/bin/perl -w

use strict;

my $input = <STDIN>;

open FILE, "numbers.txt" or die $!;
while ( <FILE> ) {
    if ( $_ =~ m/($input)/ ) {
        print $_;       
    }
}
close FILE;

 
Thanks for the above program. But there is a problem with it as it only returns the number that it matches exactly. For example if I enter 123476 then it will only return this. But if I enter 123 then it does not return anything. Any ideas?
 
When I run the program, after inputting the number I get a a blank screen. This is what I have so far.:

#!/usr/bin/perl -w

use strict;

my $input = <STDIN>;
chop $input;

open FILE, "numbers.txt" or die $!;
while ( <FILE> ) {
if ( $_ =~ m/^($input)*$/ ) {
print $_;
}
}
close FILE;
 
Code:
#!/usr/bin/perl -w

use strict;

chop( my $input = <STDIN> );

open FILE, "numbers.txt" or die $!;
while ( <FILE> ) {
    if ( $_ =~ m/($input)/ ) {
        print $_;
    }
}
close FILE;

 
I have another issue that I have been trying to solve. If numbers.txt contains entries like:

123456_A
123456_B

123444_A
123444_B

123476_A
123476_B

So bascially for every number there should be _A and _B entries in the file. If not then this should be printed to the screen. Therefore, this time the user would not enter a number but would instead just execute the script which would produce a list of entries that have either a _A or _B missing. Any ideas??? Is there a diff like function in Perl I could use?
 
well, what have you tried? This is not a script writing service although "Deleted" was nice enough to just write you a script.

Hint: use a regexp to see if there is a _A or _B on the end of the string or not:

Code:
print unless /_[AB]$/;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top