Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: changing the position of an element in an array

by ikegami (Patriarch)
on Nov 17, 2005 at 07:19 UTC ( [id://509321]=note: print w/replies, xml ) Need Help??


in reply to changing the position of an element in an array

Finding the position could be done as follows:

my ($pos) = grep { ... } 0..$#array;

where ... checks $array[$_] for the condition.

Once you find the position,

push(@array, splice(@array, $pos, 1))

will do the trick nicely.

Replies are listed 'Best First'.
Re^2: changing the position of an element in an array
by nobull (Friar) on Nov 17, 2005 at 17:48 UTC
    Actually a simple splice/push will not change the position of an element in an array, it will create a new element that comtains a copy of the value from the old of element.
    my @array = ( 'foo', 'bar', 'baz' ); my ($pos) = grep { $array[$_] eq 'bar' } 0..$#array; my $ref_to_element = \$array[$pos]; push (@array, splice(@array, $pos, 1)); print "@array\n"; # Prints 'foo baz bar' $$ref_to_element = 'zap'; print "@array\n"; # Still prints 'foo baz bar'

    Had $array[1] been moved to the end of the array then $$ref_to_element would point to $array[2] after the move.

    Admittedly, this is usually not an issue.

    On the rare occasions when you really want to move elements of an array use Array::Splice. In the above example you would use push_aliases() in place of the built-in push().

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-19 06:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found