rovf has asked for the wisdom of the Perl Monks concerning the following question:
Please suggest how to improve my code. My function lchompx basically removes several occurences of a certain string from the beginning of another string. For example, $r=lchompx('abababcdef','ab') sets $r to 'bcdef'. The details, however, are tricky:
Here is my implementation:
This seems to work, butit is ugly, since the substitution expression has to be repeated for the special case "Changing $_ in place". Any idea how to code this in a nicer way?sub lchompx { my $lchompstr=quotemeta(@_ > 0 ? $_[-1] : "\n"); my $change_in_place=!defined wantarray; my $default_argument=(@_<2); unless($change_in_place) { @_ = $default_argument ? $_ : @_; } if($change_in_place && $default_argument) { s/^($lchompstr)*// } else { $_[0] =~ s/^($lchompstr)*// } $_[0] }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How can I avoid code repetition here
by moritz (Cardinal) on Oct 07, 2009 at 12:48 UTC | |
|
Re: How can I avoid code repetition here
by ikegami (Patriarch) on Oct 07, 2009 at 16:43 UTC | |
|
Re: How can I avoid code repetition here
by Bloodnok (Vicar) on Oct 07, 2009 at 13:08 UTC | |
by rovf (Priest) on Oct 07, 2009 at 13:19 UTC | |
by JadeNB (Chaplain) on Oct 17, 2009 at 21:35 UTC | |
|
Re: How can I avoid code repetition here
by bv (Friar) on Oct 07, 2009 at 16:24 UTC | |
by rovf (Priest) on Oct 08, 2009 at 09:41 UTC | |
|
Re: How can I avoid code repetition here
by JavaFan (Canon) on Oct 07, 2009 at 16:12 UTC | |
by rovf (Priest) on Oct 08, 2009 at 09:35 UTC | |
by JavaFan (Canon) on Oct 08, 2009 at 09:48 UTC | |
by rovf (Priest) on Oct 08, 2009 at 10:56 UTC | |
by JavaFan (Canon) on Oct 08, 2009 at 11:45 UTC | |
|