Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
Here's my shot at it:
#!/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 );


Update: I realize that the line that generates $index is a potential point of failure via false positives (matching "10" when $bad = 1, for example). However, I've discussed this with the OP and he says it's not an issue, due to the fact that the values are all 4-digit numbers.

Update 2: The above statement no longer applies post-patch.

---
It's all fine and dandy until someone has to look at the code.

In reply to Re: replacing order element in array by kwaping
in thread replacing order element in array by scoobyrico

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2021-11-29 00:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?