Rabu, 25 Agustus 2010

Random Perl wishlists #1: uncapture modifier, require+import, backtick function

Uncapture modifier. The new /r regexp substitution modifier in Perl 5.13.2 indicates that there might be hope for even more modifiers in the future. A possible modifier might be one that ignores all capture groups, which can solve this guy's problem.

require that can also import. I wonder why "require" doesn't also support importing like "use" does: use MODULE_NAME LIST... since it already support "require MODULE_NAME". This way, whenever I want to defer loading some modules, I can just replace "use" with "require" and put the statement under some "if" statement.

the backtick function.. Do you find yourself often having to do use a temporary variable like this, $cmd = "some longish and ".quote("complexly formed")."command"; before doing backtick `$cmd`? This is because unlike in PHP, we have system() but no backtick(). Most probably remnants from shell. There is Capture::Tiny for more general solution but of course it's a bit more cumbersome.

5 komentar:

  1. "Uncapture modifier"
    this guy using bracers, but they doesn't needed. Problem is silly. Show real example with problem and we discuss it.

    "require that can also import"
    why you don't use 'use'?

    "the backtick function"
    you can use interpolation of scalar expression
    `${\ "some longish and ".quote("complexly formed")."command" }`

    BalasHapus
  2. @zloyrusskiy A require that calls import would happen at runtime rather than in the BEGIN phase, this could be useful, but it is easy enough to write for yourself:

    sub runtime_use {
        my $package = shift;
        require $package;
        $package->import;
    }

    BalasHapus
  3. @zloyrusskiy: Thanks for the tip on interpolating scalar expression, I tend to forget this useful feature of Perl nowadays.

    As for uncapturing the captures, it can be useful when we compose regexes from other regexes, and the other regexes come from outside/written by other people. Example:

    $email_re = /^($user_re)\@($domain_re)$/

    and I take $user_re and $domain_re from somewhere else, and I need to make sure that $1 and $2 contains what I want.

    BalasHapus
  4. Oops, forgot to add qr//, and nice/modular regex should not contain capture groups unless really necessary anyway, but the point remains.

    BalasHapus
  5. @Steven Haryanto

    you can use "named captures" to avoid this problem

    BalasHapus

Catatan: Hanya anggota dari blog ini yang dapat mengirim komentar.