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

Hi I am new to perl. I need to append some string to one array. How to do this? My code is like this foreach my $server (keys %{$newHosts->{server}}) { # some junk code in between and I want to append String "IP" to newHosts->server } I wanna append one string say IP to newHosts->{server}. ( if newHosts->server is some IP like 10.100.200.10, I want output like IP_10.100.200.10. Please help me. Thanks in advance.

Replies are listed 'Best First'.
Re: array manipulation with string
by ELISHEVA (Prior) on Sep 24, 2009 at 06:43 UTC

    Welcome to PerlMonks!, santoshkumarcp

    It will be easier for people to help you if you surround your code (e.g. the part after My code is like this...) with <code>...</code> tags. This will make your code look more like it looks when you type it into the input box. If you can't see the edit box, scroll down a bit in your browser window. If you still can't see it, click on the title of your post.

    As for the question itself: you can use the concatenation (dot) operator 'IP_' . $newHosts->{server} to get the sting "IP_10.100.200.10". Further discussion aimed at a beginner can be found at How to concatenate stings with Perl.

    Best, beth

Re: array manipulation with string
by irah (Pilgrim) on Sep 24, 2009 at 06:29 UTC

    Please use code tag, for posting the code.

    You can use dot (.) operator for concatenate the strings in Perl.

Re: array manipulation with string
by jwkrahn (Abbot) on Sep 24, 2009 at 08:18 UTC
    s/^(?=\d+\.\d+\.\d+\.\d+)/IP_/ for values %{ $newHosts->{ server } };
      Hmmm ,

      The OP would like the existing IP address prefixed with i.e. not replaced by, the string 'IP_', viz:

      s/^/IP_/ for values %{ $newHosts->{ server } };
      or
      $_ = q/IP_/ . $_ for values %{ $newHosts->{ server } };
      A user level that continues to overstate my experience :-))

        jwkrahn's code is not doing a replacement because his pattern is inside a zero-width positive look-ahead assertion, i.e. it is in effect doing an insertion at a point in the string that is followed by the pattern because the item being substituted is zero-width.

        Cheers,

        JohnGG