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

Re^2: Inserting an element into an array after a certain element

by Roy Johnson (Monsignor)
on Mar 31, 2005 at 21:07 UTC ( [id://443973]=note: print w/replies, xml ) Need Help??


in reply to Re: Inserting an element into an array after a certain element
in thread Inserting an element into an array after a certain element

Maybe factor out the common $front in each return statement to make one return statement:
sub insert_after_first { return if @_ < 3; my ( $elem, $new, $front ) = splice @_, 0, 3; return ( $front, $front eq $elem ? ($new, @_ ) : insert_after_first( $elem, $new, @_ ) ); }
Update: Oo! In fact, you don't do anything with $new, except stick it back on the front of @_, so don't take it off:
sub insert_after_first { return if @_ < 3; my ( $elem, $front ) = (splice(@_, 0, 1), splice(@_, 1, 1)); return ( $front, $front eq $elem ? @_ : insert_after_first( $elem, @_ ) ); }
Then, to change Lispish elegance to Perlish elegance (or madness), make your argument list the way you want it for the recursion, and use & without parentheses to recurse:
sub insert_after_first { return if @_ < 3; my $front = splice(@_, 2, 1); return ( $front, $front eq $_[0] ? @_[1..$#_] : &insert_after_first ); }

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^3: Inserting an element into an array after a certain element
by kelan (Deacon) on Mar 31, 2005 at 21:27 UTC

    Getting a bit unreadable, though, I'd say. ;)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-19 13:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found