Is there a way to precompile a regex in Perl?

后端 未结 3 2115
刺人心
刺人心 2020-12-08 14:11

Is there a way to precompile a regex in Perl? I have one that I use many times in a program and it does not change between uses.

3条回答
  •  难免孤独
    2020-12-08 14:54

    for clarification, you can user precompiled regex as:

    my $re = qr/foo|bar/;  #precompile phase
    if ( $string =~ $re ) ...   #for direct use
    if ( $string =~ /$re/ ) .... #the same as above but a bit complicated
    if ( $string =~ m/something $re other/x ) ...  #for use precompiled as a part of bigger regex
    if ( $string =~ s/$re/replacement/ ) ...  #for direct use as replace
    if ( $string =~ s/some $re other/replacement/x ) ... #for use precompiled as a part of bigger, and as replace all at once
    

    It is documented in perlre but there are no direct examples.

提交回复
热议问题