in reply to Idiom for a regex translation

I think there are two main options: squish the assignment and modification together, or make a subroutine. For clarity I'd usually recommend the latter:

(my $squished_name = $name) =~ s/\W//g; my $squished_name = squish($name);

Hugo

Replies are listed 'Best First'.
Re^2: Idiom for a regex translation
by reasonablekeith (Deacon) on Apr 22, 2005 at 09:54 UTC
    But the subroutine just moves the problem somewhere else. Also, I think a single regex is too simple to warrant a subroutine of it's own.
    sub squish { my $unsquished = shift; .. what do you put here? return $squished; }

      sub squish { my $copy = shift; $copy =~ s/\W//g; return $copy; }

      It is not the action (the substitution) that warrants the subroutine, but the concept ("squish"). It is never the simplicity of the action that determines whether the concept is "too simple to warrant a subroutine of its own" - for example, it would be useful to do this if you were using squish() in several places in the code but might want to change it in the future, or add diagnostics etc.

      But even if it will only ever be used once, putting a block of code into a named subroutine is a very useful technique for writing self-documenting code, by associating the relevant concept with the code through the name of the subroutine.

      Hugo

        You are of couse right, if I was squishing lots of things a subroutine would be warrented (duplication eq bad).

        I would argue, however, that a variable going from $name into $squished_name is sufficiently self-documenting as to not warrent a sub.

        Thanks for your comments.

      sub squish { ( my $squished = shift ) =~ s/\W+//g; return $squished; }
      But I also would not use a separate sub for this one.

      the lowliest monk