Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Stepping through an array and making changes "as-you-go" has unforeseen problems. We get quite a few "Why didn't this work?" questions related directly to attempting to do this type of thing.

The issue is actually documented in "perlsyn: Foreach Loops" and specifically mentions splice:

"If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that."

[In case you didn't know, for and foreach are synonymous.]

So, you'd need to do something like the following.

sub splice_unique2 { my @sorted = sort qw{q w e r t y q w e r t y}; my $last = ''; my @unique = @sorted; my $removed = 0; for (0 .. $#sorted) { if ($sorted[$_] eq $last) { splice @unique, $_ - $removed++, 1; } else { $last = $sorted[$_]; } } }

I plugged that in to my earlier benchmarking script. Here's a representative result:

Rate splice_unique2 splice_unique shift_unique +map_unique splice_unique2 83836/s -- -10% -15% + -28% splice_unique 92839/s 11% -- -6% + -20% shift_unique 99211/s 18% 7% -- + -14% map_unique 115924/s 38% 25% 17% + --

My coding of splice_unique2() was really just intended to show a way to get around the documented issue. If you think the task has any merit, feel free to try to rewrite it to run faster.

-- Ken


In reply to Re^6: Create unique array --the hard way! by kcott
in thread Create unique array --the hard way! by Anonymous Monk

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 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?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-25 17:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found