Tim
Tim

Reputation: 14154

How should I shorten simple substitution subroutines?

sub my_sub {
    my $str = shift;
    $str =~ s/some/regex/;
    return $str;
}

Five lines seems too long for such a simple subroutine. Can it be simplified, e.g. by not using an intermediary variable?

Upvotes: 1

Views: 187

Answers (3)

brian d foy
brian d foy

Reputation: 132783

That isn't long for a simple substitution. It's also creating a copy of the data, substituting on that copy, and returning the modified copy while leaving the original alone. So, you'd use it like this:

 my $modified = my_sub( $original );

Some of the answers work on $_[0], the first item in @_. This is an alias to the original data. This way, Perl doesn't have to copy the data until it knows you actually need a separate copy. When you do the substitution on the alias, you modify the original. Doing that is more like changing the original and assigning back to it:

 $original = my_sub( $original );

The question you ask, though, is to make it shorter. That's usually not a good enough reason to do anything. It's a subroutine, so let it be as long as it likes when it meets your requirements. Before you design this sort of code, figure out what your requirements are.

Upvotes: 1

MkV
MkV

Reputation: 3096

sub my_sub {
    (my $str = shift) =~ s/some/regex/;
    $str;
}

Upvotes: 3

zb226
zb226

Reputation: 10500

Without intermediary variable and one line shorter:

sub my_sub {
    $_[0] =~ s/some/regex/;
    return $_[0];
}

Edit: As @pavel noted, this will modify the original variable.

Since Perl 5.13.2, there is the non-destructive modifier /r (for reference, see perlop), which will not modify the variable the regex operates on - this also allows to ditch another line:

sub my_sub {
    return $_[0] =~ s/some/regex/r;
}

Upvotes: 9

Related Questions