Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How to remove the certain element of an object

by sundialsvc4 (Abbot)
on Feb 04, 2013 at 15:40 UTC ( [id://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.

Replies are listed 'Best First'.
Re^2: How to remove the certain element of an object
by vagabonding electron (Curate) 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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1016962]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-03-28 14:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found