Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
The code I have works well, but I'm not entirely happy with it, so I would be glad to learn how it can be improved (shorter/clearer). This is a bit like a "programming exercise" I made up for myself, although I stumbled over this problem when writing a production program.

Problem: I have an even-sized array, with the property that the odd-numbered elements are never undef. This array should be processed left-to-right, two elements at a time, in a loop. The elements to be processed should be removed from the list. My solution goes like this:

# Array to be processed: @arr while(defined( ( my ($x,$y) = (shift(@arr), shift(@arr)) )[0])){ .... }
In this code, I combine the extraction of the first two elements from the list, with testing whether the list is already empty (which would set $x and $y to undef). Since the even-sized elements in the list are allowed to be undef, I test only $x.

However, I don't like the clumsy defined((my (...) ...)[0]). I would prefer a solution which looks as clean as the <c>each generator used to iterate over the elements of a hash. If I had this type of problem more frequently, I would perhaps write my own generator, but it would be overkill in this case. Maybe there is any other way I could improve my code?
-- 
Ronald Fischer <ynnor@mm.st>

In reply to Processing pairs of values from even-sized array by rovf

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 avoiding work at the Monastery: (3)
As of 2024-04-19 23:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found