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

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

by kelan (Deacon)
on Mar 31, 2005 at 20:15 UTC ( [id://443956]=note: print w/replies, xml ) Need Help??


in reply to Inserting an element into an array after a certain element

If elegance is more important than effeciency, try this recursive version:

sub insert_after_first { return if @_ < 3; my ( $elem, $new, $front ) = splice @_, 0, 3; return ( $front, $new, @_ ) if $front eq $elem; return ( $front, insert_after_first( $elem, $new, @_ ) ); }
Otherwise, I'd say just keep the version that you've got, although I'd change the loop initialization to for (0 .. $#arr), like ikegami shows above.

Replies are listed 'Best First'.
Re^2: Inserting an element into an array after a certain element
by Roy Johnson (Monsignor) on Mar 31, 2005 at 21:07 UTC
    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.

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

Re^2: Inserting an element into an array after a certain element
by kelan (Deacon) on Mar 31, 2005 at 21:24 UTC

    The Perl6 version is about the same:

    sub insert_after_first( $elem, $new, *@data ) { return if @data.elems < 1; my $front = @data.shift; return ( $front, $new, *@data ) if $front ~~ $new; return ( $front, insert_after_first( $elem, $new, *@data ) ); }
    I thought the parameter naming being specified in the declaration would help, but you still neet to shift the front element off of the data list for comparison or it gets real ugly.

Log In?
Username:
Password:

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

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

    No recent polls found