in reply to Re: perl regular expressions
in thread perl regular expressions

Can i find multiple strings with the code that you mentioned. find_string('filename', "testing,link,rd"); I need to search multiple strings in the same function

Replies are listed 'Best First'.
Re^3: perl regular expressions
by kennethk (Abbot) on Jun 23, 2014 at 23:30 UTC
    Rather than calling the code as
    find_string('filename', "testing,link,rd");
    for as I've written it, you'd invoke it with
    find_string('filename', "testing","link","rd");
    Alternatively, you could add a split to my proposed solution.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      thanks for the info,I was wondering if i had to use any perl cpan modules for map and join to work.

        No installation necessary; those are all CORE.


        #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Thanks for the info.I was wondering if i had to install perl cpan modules for join and map to work?
      Hello,The script is not working.I get the following error:

      Global symbol "$string" requires explicit package name at map.pl line 13. Execution of map.pl aborted due to compilation errors. Use of uninitialized value $file in open at map.pl line 8. readline() on closed filehandle $fh at map.pl line 9.

      I see that you have used @string but I see $string in die "Unable to find string: $string";

      use strict; use warnings; find_string { my ($file, @strings) = @_; open my $fh, '<', $file; my $re = join "|", map quotemeta, @strings; while (<$fh>) { return 1 if /$re/; } die "Unable to find string: $string"; } find_string('prepos.config', "testing","link","100K");
        Sorry, my oversight. The offensive line is the die, which should be updated to read (perhaps):
        die "Unable to find string(s): @strings";

        #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Still not working. Not enough arguments for read near ""Unable to find string: @strings";" Execution of .pl aborted due to compilation errors.
        I do not see that error; what is the exact code you have?
        sub find_string { my ($file, @strings) = @_; open my $fh, '<', $file; while (<$fh>) { for my $string (@strings) { return 1 if /\Q$string/; } } die "Unable to find string: @strings"; } find_string('filename', "testing","link","rd");
        Of course the above should be amended to test that the open worked:
        open my $fh, '<', $file or die "File open fail ($file): $!";

        #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.