Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I golf this Perl subroutine that does a substitution?

Tags:

perl

I have the following subroutine in Perl to substitute "abc" for "xyz" in a string:

sub mySubst {
    my ($str) = @_;
    $str =~ s|abc|xyz|ig;
    return $str;    
}

It works, but seems way too verbose for Perl. How can I tighten it up?

like image 280
JoelFan Avatar asked Nov 30 '22 06:11

JoelFan


1 Answers

What you have is fine.

  • You pull the arguments off the @_ variable, making a copy, using a list assignment. List assignment is an excellent way to do it (and basically the standard way.) Using shift would also work, but changes @_ (may or may not be what you want.) There's a discussion on PerlMonks about shift vs @_ that you might be interested in.
  • You use a named variable with your search and replace. I prefer named variables in this case, since dealing with Perl's magic variables takes care.
  • Automatically working on $_ would be possible, but not having $_ auto populated makes it trickier to get right. You'd need to do local $_ = shift; or local ($_) = @_; which doesn't add much.)
  • I like it when people use an explicit return. It's a warm fuzzy.
  • K&R Brackets. Good. :)
  • No prototype. Very good. :)

Go with it. I think you're on the right track.

like image 124
Robert P Avatar answered Mar 27 '23 04:03

Robert P