Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: How to remove the certain element of an object

by sundialsvc4 (Abbot)
on Feb 04, 2013 at 15:40 UTC ( #1016962=note: print w/replies, xml ) Need Help??

in reply to How to remove the certain element of an object

Personally, I would reject the present purge_this_one subroutine in a code review.   I’d do it because phrasing such as $_[n], while syntactically acceptable to Perl, most certainly is not informative to me, nor to anyone else who might encounter this code in the future.   I’d have to examine each and every use of the subroutine in order to figure out either how to call it correctly or how to debug it.

Furthermore, the code is trusting.   What if $idx is undefined (or whatever) because the element isn’t there at all?   The code doesn’t work anymore, and it doesn’t say why it doesn’t.

Take the extra few microseconds it takes to write code that is legible, maintainable by someone other than yourself, and capable of responding at least with respect to the Hippocratic Oath if the program contains an error elsewhere.   You will be very glad that you did.

  • Comment on Re: How to remove the certain element of an object

Replies are listed 'Best First'.
Re^2: How to remove the certain element of an object
by vagabonding electron (Chaplain) on Feb 04, 2013 at 16:23 UTC

    Dear sundialsvc4

    thank you! Of course you are right. If the search element is not in the array then $idx is -1 and the subroutine just removes the last element of the array.

    A quick solution could be to add the line

    return @{$_[0]} if $idx == -1;

    above "splice"

    Here is a version which should be more readable:

    sub purge_this_one { my $aref = $_[0]; my $searched = $_[1]; my $idx = first_index { $_ == $searched } @$aref; return @$aref if $idx == -1; splice( @$aref, $idx, 1 ); return @$aref; }

    Thanks again!

    Update:Well, it is not enough since the subroutine does not tell if it does not purge anything. It should warn at least. I take it home and try to make it better. Thank you for noticing this. Update:Removed some private lyric from the original text.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016962]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2018-05-28 06:28 GMT
Find Nodes?
    Voting Booth?