in reply to store regex in hash

Sorry didnt read how to format post

I am trying (big emphasis on trying ) to write a script to parse log files, I thought it would be a good idea to store the regex in a hash table and use the event ID as the key. So that I can add to the hash table as new log messages types are added.

My problem is that I get the regex string working properly but when I put it in a variable it stops working, a quick example is the regex to extract the event ID

#this works: $current_line =~ q{\A.*? %(.*?): }xms; $event_id = $1; #this fails: $RGX_EVENTID = 'q{\A.*? %(.*?): }xms'; $current_line =~ $RGX_EVENTID; $event_id = $1;

Replies are listed 'Best First'.
Re^2: store regex in hash
by graff (Chancellor) on Jul 03, 2011 at 18:08 UTC
    Try it like this:
    $RGX_EVENTID = qr{\A.*? %(.*?): }xms; if ( $current_line =~ /$RGX_EVENTID/ ) { print "got event_id //$1// from input //$_//\n"; }
    Note the use of the qr operator to assign a regex-like string to $RGX_EVENTID, and the use of normal regex match delimiters around that variable when applying the match to another string. (You need to be careful about using regex delimiters that either don't occur within the regex itself, or are properly escaped when they do occur.)

    Also, I think it's better to update your OP to fix the formatting there, rather than creating a reply that fixes the formatting.

    Update: forgot to mention... Welcome to the Monastery! "OP" refers to "original post" (top of the thread).

      and the use of normal regex match delimiters around that variable when applying the match to another string.

      The use of regex match delimiters is not actually necessary when matching against a string as the binding operator provides the context to use the compiled regex. They are needed if doing a default match against $_ without a binding operator.

      knoppix@Microknoppix:~$ perl -E ' > $rx = qr{(\d+)}; > > $str = q{ab12ef}; > $_ = q{gh34kl}; > > say $1 if $str =~ $rx; > say $1 if $rx; > say $1 if m{$rx}; > > $_ = q{mn56qr}; > > say $1 if $_ =~ $rx;' 12 12 34 56 knoppix@Microknoppix:~$

      I hope this is of interest.

      Cheers,

      JohnGG

Re^2: store regex in hash
by JavaFan (Canon) on Jul 03, 2011 at 20:26 UTC
    #this works: $current_line =~ q{\A.*? %(.*?): }xms; $event_id = $1;
    Really? I don't think it even compiles.