Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Providing regex using an array

by dgrunwal (Initiate)
on Sep 09, 2022 at 21:55 UTC ( [id://11146798]=perlquestion: print w/replies, xml ) Need Help??

dgrunwal has asked for the wisdom of the Perl Monks concerning the following question:

Perl Monks, I am trying to use an array to list regex search choices. Code works if a single regex is inputted.
use strict; use warnings; sub main { my @patterns = ("^abd", "ghi"); my $file = 'C:\Perl64\bin\hello.txt'; open(FH, $file) or die("File $file not found"); while(my $String = <FH>) { # if($String = ~ /^abd /) if($String .= join ('/ && /', @patterns); { print "$String \n"; } } close(FH); } main();
Error: Global symbol "@patterns" requires explicit package name at pattern2.pl line 7. Global symbol "@patterns" requires explicit package name at pattern2.pl line 14. syntax error at pattern2.pl line 14, near ");" Execution of pattern2.pl aborted due to compilation errors. What syntax error am I making? Best, David

Replies are listed 'Best First'.
Re: Providing regex using an array
by haukex (Archbishop) on Sep 09, 2022 at 22:12 UTC

    You have unbalanced parens in your if, the semicolon on that line should be a closing paren.

    If I understand correctly what your code is trying to do, you may be interested in my tutorial Building Regex Alternations Dynamically.

Re: Providing regex using an array
by LanX (Saint) on Sep 10, 2022 at 00:17 UTC
    First of all please fix your indentation, you seem to be mixing spaces and tabs.

    This might look ok in your editor, but your tab-length is 8 while we use 4 here.

    It's hard to tell what you are trying to achieve, my best guess is to check that all regexes in an array individually match.

    the following debugger-demo is using the fact that grep returns a count in scalar context

    > perl -de0 DB<134> @patterns = ("^abd", "ghi"); DB<135> $string = "abd__ghi__" DB<136> p @patterns == grep { $string =~ $_ } @patterns 1 DB<137> DB<137> $string = "abd__xhi__" DB<138> p @patterns == grep { $string =~ $_ } @patterns DB<139>

    even easier if you use all from List::Util

    DB<139> use List::Util qw/all/ DB<140> $string = "abd__ghi__" DB<141> p all { $string =~ $_ } @patterns 1 DB<142>

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      Thank you! Best, Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11146798]
Approved by haukex
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-18 19:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found