#!/usr/bin/perl use strict; use warnings; # set up srand; my @one = (1,2,3,4,5,6); my @two = (2,4,6,8,9,12); # the value that needs replacing my $bad = 4; # figure out where that value is in list one ### my $index = index(join('',@one),$bad); # <- bad code my $index = 0; my $found = 0; foreach my $item (@one) { if ($item == $bad) { $found++; last; } $index++; } die "The value '$bad' was not found in the list\n" unless ($found); # find elements of list two that aren't already in list one my $re = join('|',@one); my @candidates = grep(! /^(?:$re)$/, @two); # replace unwanted list one value with random selection from list two $one[$index] = $candidates[rand @candidates]; use Data::Dumper::Simple; print Dumper(@one); __END__ @one = ( 1, 2, 3, 8, 5, 6 );