Can I break my Perl regex into multiple lines in my code?

前端 未结 3 1382
野性不改
野性不改 2021-01-17 08:52

I was just wondering if I am able to break up a long regular expression that I have in my Perl code so that it is written over several lines? I just want the readability an

相关标签:
3条回答
  • 2021-01-17 09:09

    Use the Whitespace-Insensitive Modifier

    The perlre(1) manual page says:

    The "/x" modifier itself needs a little more explanation. It tells the regular expression parser to ignore most whitespace that is neither backslashed nor within a character class. You can use this to break up your regular expression into (slightly) more readable parts.

    You can use this to create multiline expressions. For example:

    /
      abcde_abcde_abdcae_adafdf_    # Have some comments, too. 
      abscd_casdf_asdfd_....asdfaf  # Here's your second line.
    /x
    

    Literal Spaces

    If your match will contain spaces, you need to make them explicit in your regular expression when using the /x modifier. For example, /foo bar baz quux/x won't match a space-separated string the way you might expect. Instead, you need something like the following:

    print "true\n" if
        /
            foo
            \s+  # You need explicit spaces...
            bar
            \s+  # because the modifier will...
            baz
            \s+  # otherwise ignore literal spaces.
            quux
        /x;
    
    0 讨论(0)
  • 2021-01-17 09:12

    Use the + symbol. Here is example:

    push @steps, $steps[-1] +
            $radial_velocity * $elapsed_time +
            $orbital_velocity * ($phase + $phase_shift) -
            $DRAG_COEFF * $altitude;
    
    0 讨论(0)
  • 2021-01-17 09:18

    Yep, see the /x modifier in the perlre man page.

    0 讨论(0)
提交回复
热议问题