in reply to perl regular expressions

If you want to return a binary found/not found, you can just modify your code to use an alternator:
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"; }
or, if you're not really comfortable with join and map,
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: $string"; }

As a side note, it's usually good to wrap input in <code> tags as well, since HTML and perlmonks will collude to mangle your offering.


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

Replies are listed 'Best First'.
Re^2: perl regular expressions
by iamsachin (Initiate) on Jun 23, 2014 at 23:25 UTC

    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

      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.

        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");
        Still not working. Not enough arguments for read near ""Unable to find string: @strings";" Execution of .pl aborted due to compilation errors.