Question

How can i search from set of strings

i would like a perl script to search for either "aaa", "bbb", "ccc", "ddd"

Searching from txt file

Example 1

some random text
blah
blah 
blah
//Car/trunk/sandbox/users/Tom/xyz/bbb/toyota

Desired Output:

//Car/trunk/sandbox/users/Tom/xyz/...

Example 2

some random text
blah
blah 
blah
//Car/trunk/sandbox/users/Alex/abc/defg/ddd/honda/accord

Desired Output:

//Car/trunk/sandbox/users/Alex/abc/defg/...

Basically searching from the given set of strings from "aaa", "bbb", "ccc", "ddd" it finds "bbb" in example 1 and takes everything before and adds back slash with "..."

Please note that it is reading from one text file, example 1 is a example of text file and same goes for example 2.

So far this is what i have.

my $infile = 'new5.txt';
    my @strings  = qw/aaa bbb ccc ddd/;
    local @ARGV = ($infile);
    while( <> ){

        print;
    }
Was it helpful?

Solution

The code you have so far is what I would call a hackish way to cat a file. First of all, we will get the obligatory pragmas out of the way:

use strict;
use warnings;
use autodie;

The last one makes sure the script dies if a file was not found or could not be opened. You initialized $infile and @strings correctly, good.

The proper or more accepted way to open and loop over the contents of a file is this:

open(my $FILE, "<", $infile);
while(my $line = <$FILE>) {
   chomp $line;
   ...
}
close($FILE);

Within this loop you want to try to match each element of the @strings array. That can be accomplished by looping over each element in the array:

foreach my $elem (@strings) {
    ...
}

In this loop you want to do the match. If it does, print out what you need (and go the next line in the file). Look up the perlre man page to see what the stuff after =~ is doing:

if ($line =~ m#/$elem/#) {
    print SOMETHING;
    next;
}

What would that SOMETHING be? According to the perlvar man page, `$`` (among other mnemonics) is the variable that contains the string before the matched string:

print $`."/...\n";

Put it all together and you have your script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top