Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Will the sorting order of an array used in producing new arrays be retained?

by jospan (Novice)
on Oct 09, 2012 at 21:02 UTC ( #998076=perlquestion: print w/ replies, xml ) Need Help??
jospan has asked for the wisdom of the Perl Monks concerning the following question:

Oh Elders of Perldom, Wizards of Code and Masters of the Divine Editor enligthen a simple novice please! :)

I have an array (hereafter known as The Master Array).

The array is sorted.

I produce new arrays as subsets of The Master Array by using grep.

My question(s) is this:

1) will the subset arrays still be sorted as The Master Array or will I have to re-sort the subset arrays if I wish to ensure that these are sorted?

2) Whatever the answer to 1): can the answer be generalized to all cases where a function (say map) is used to produce arrays from a sorted master array?

Comment on Will the sorting order of an array used in producing new arrays be retained?
Re: Will the sorting order of an array used in producing new arrays be retained?
by hippo (Deacon) on Oct 09, 2012 at 21:21 UTC

    Very quick answers:

    1. Yes.
    2. Yes, so long as your function doesn't monkey with the order.

    Good luck!

Re: Will the sorting order of an array used in producing new arrays be retained?
by AnomalousMonk (Monsignor) on Oct 09, 2012 at 22:24 UTC

    For question 1: In general, WRT grep (which can only remove elements): yes, the relative order is maintained. For Far More Than You Ever Wanted to Know about this, see the recent Order in which grep/map receive elements.

    For question 2: In general, WRT map (which is allowed to insert elements) the answer is no:

    >perl -wMstrict -le "my @sorted = (1, 2, 3, 4, 5, 6); my @unsorted = map { $_, 99 } @sorted; print qq{@unsorted}; " 1 99 2 99 3 99 4 99 5 99 6 99
      Thank you both for the quick reply - I appreciate it!
Re: Will the sorting order of an array used in producing new arrays be retained?
by linuxkid (Sexton) on Oct 09, 2012 at 22:53 UTC

    Define 'Divine Editor.' You do mean Emacs right?

    --linuxkid


    imrunningoutofideas.co.cc
      I sense the dawning of yet another flame war! :D .. allow me to defuse it: 'Divine Editor' <= insert your personal favourite editor here...

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://998076]
Approved by Marshall
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2014-07-10 05:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (199 votes), past polls