Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Frequently I find that I want to create a variable that resembles a currently existing variable but with a substitution applied. Invariably, this is the way I do it:
$ExistingVariable = "SuperMan"; $NewVariable = $ExistingVariable; $NewVariable=~s/^Super//;
Is there a way to say something like $NewVariable eq whatever $ExistingVariable would be if I applied s/^Super// to it? Does that make sense? Does this have to take up three lines or can I do it in one?

Replies are listed 'Best First'.
Re: Substitution question
by broquaint (Abbot) on Apr 14, 2003 at 15:05 UTC
    Is there a way to say something like $NewVariable eq whatever $ExistingVariable would be if I applied s/^Super// to it?
    But of course
    my $str1 = "SuperMan"; print $str1, $/; (my $str2 = $str1) =~ s{^Super}(); print $str2, $/; __output__ SuperMan Man

    HTH

    _________
    broquaint

Re: Substitution question
by Abigail-II (Bishop) on Apr 14, 2003 at 15:08 UTC
    I don't see what's so bad in writing in in three lines, but you could also write like this:
    ($new = $old = "SuperMan") =~ s/^Super//;

    Of course, this mostly boils down your three lines with the newlines and some other bits taken out.

    Abigail

Re: Substitution question
by Anonymous Monk on Apr 14, 2003 at 15:11 UTC
    Wow. Thanks. That's cool. There's a bit that I don't quite understand, though.
    s{^Super}.()
    I understand that one can use something other than / to delimit a substitution
    s/this/that/ or s!this!that!
    but what is the () there on the end?
      but what is the () there on the end?
      You can use also use balanced character delimiters. See. the Quote and Quote-like Operators of perlop for more info.
      HTH

      _________
      broquaint