Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an analogue of Ruby gsub method in Perl? [duplicate]

Tags:

perl

Possible Duplicate:
How do I perform a Perl substitution on a string while keeping the original?

How do I do one line replacements in Perl without modifying the string itself? I also want it to be usable inside expressions, much like I can do p s.gsub(/from/, 'to') in Ruby.

All I can think of is

do {my $r = $s; $r =~ s/from/to/; $r}

but sure there is a better way?

like image 841
vava Avatar asked Dec 08 '25 01:12

vava


2 Answers

Starting on the day you feel comfortable writing use 5.14.0 at the top of all of your programs, you can use the s/foo/bar/r variant of the s/// operator, which returns the changed string instead of modifying the original in place (added in perl 5.13.2).

like image 132
hobbs Avatar answered Dec 10 '25 16:12

hobbs


The solution you found with do is not bad, but you can shorten it a little:

do {(my $r = $s) =~ s/from/to/; $r}

It still reveals the mechanics though. You can hide the implementation, and also apply substitutions to lists by writing a subroutine. In most implementations, this function is called apply which you could import from List::Gen or List::MoreUtils or a number of other modules. Or since it is so short, just write it yourself:

sub apply (&@) {                  # takes code block `&` and list `@`
    my ($sub, @ret) = @_;         # shallow copy of argument list 
    $sub->() for @ret;            # apply code to each copy
    wantarray ? @ret : pop @ret   # list in list context, last elem in scalar
}

apply creates a shallow copy of the argument list, and then calls its code block, which is expected to modify $_. The block's return value is not used. apply behaves like the comma , operator. In list context, it returns the list. In scalar context, it returns the last item in the list.

To use it:

my $new = apply {s/foo/bar/} $old;

my @new = apply {s/foo/bar/} qw( foot fool fooz );
like image 35
Eric Strom Avatar answered Dec 10 '25 14:12

Eric Strom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!