6

I have a array i want to to replace a particular value if exists in the array with a specific value .

Array

my @array_list = ('TEST12','TEST14','TEST','TEST23');

What i have tried is :

foreach (@array_list) { 
    if($_ eq "TEST"){
        $_ =~ s/$_/HT/;
    }
 } 

Is there any other better way to do this .Please help me in this

4
  • 1
    @array_list = map { $_ eq 'TEST' ? 'HT' : $_ } @array_list Commented Aug 26, 2014 at 7:58
  • Or another... @array_list = map { s/^TEST$/HT/; $_ } @array_list Commented Aug 26, 2014 at 8:09
  • @DavidO while this works, it has side effect when assigning to another array as $_ inside map is aliased to original array. Commented Aug 26, 2014 at 11:01
  • @mpapec Yes but we assign back to the original, nullifying the side-effect. :) But you're correct; if we wanted to make it safe in a general sense, we would make a copy before the substitution. Commented Aug 26, 2014 at 14:38

1 Answer 1

8

Assuming you just want to do in-place replacement of the single exact match:

use strict;
use warnings;

my @array_list = ('TEST12','TEST14','TEST','TEST23');

$_ eq 'TEST' and $_ = 'HT' for @array_list;

use Data::Dump;
dd @array_list;

Outputs:

("TEST12", "TEST14", "HT", "TEST23")

Can accomplish the same with a regex as well:

s/\ATEST\z/HT/ for @array_list;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.