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

I could brute force this, but thought there might be a more elegant way. I wish to add a prefix to a string if the string does not already start with the prefix. All help much appreciated.

  • Comment on Prepent string a to string b if b does not start with a

Replies are listed 'Best First'.
Re: Prepent string a to string b if b does not start with a
by choroba (Cardinal) on Mar 14, 2012 at 11:45 UTC
    What do you mean by brute forcing this?
    $pre = "PRE"; @S = qw/Q PREQ/; s/^(?!$pre)/$pre/ for @S; say for @S;
    or
    $pre = "PRE"; @S = qw/Q PREQ/; for (@S) { $_ = $pre . $_ unless 0 == index $_, $pre; } say for @S;
Re: Prepent string a to string b if b does not start with a
by Corion (Patriarch) on Mar 14, 2012 at 11:36 UTC

    How would you brute force this?

      unless(grep(/^rte/, $ENV)) { $ENV = "rte" . $ENV; }

      This works, sorry to have distrubed anyone, and thanx

        Using grep for one-member list is strange. You can just use if ($ENV !~ /^rte/)
Re: Prepent string a to string b if b does not start with a
by Anonymous Monk on Mar 14, 2012 at 15:43 UTC
    Brute-force it, as you say, and move along. These aren't the 'droids you're looking for ...