http://www.perlmonks.org?node_id=1003663


in reply to Re: ordering array of sentences
in thread ordering array of sentences

Thanks,it works (couple of changes can be necessary for taking into account case, commas, etc. BUT: as I am a newbe in perl, could you "split" (i.e. putting it in simpler blocks) for me the lines

say for map $_->[1], sort { $a->[0] cmp $b->[0] } map { /(\w+)\s+searching/; [$1, $_] } @sentences;

so that I better understand its functioning. For example, I am trying to put the result of the sorting again in an array, but I can't do it. That would be great!

Replies are listed 'Best First'.
Re^3: ordering array of sentences
by choroba (Cardinal) on Nov 13, 2012 at 16:58 UTC
    As usual in functional programming, read from right to left (or bottom to top):

    The map changes the sentences to arrays of arrays. Each such an array has two elements: the word to sort on and the original sentence.

    sort just sorts the arrays according to their first element, i.e. the sort word.

    map transforms the arrays back to sentences.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      I got it. Thank you!

      In a very ugly Perl, I translated it so:

      my @sentences1 = map { /(\w+)\s+searching/; [$1, $_] } @sentences +; my @sentences2 = sort { $a->[0] cmp $b->[0] } @sentences1; my @sentences3 = map {$_->[1]} @sentences2; foreach (@sentences3) { print $_; }

      ...just to lear Perl

      What if my @sentences has a more complicated structure? I get @sentences from querying a Sqlite database with the following:

      $sentences = $dbh->selectall_arrayref("SELECT ID, sentence FROM texts +WHERE sentence REGEXP '(?i:$query)'");

      As one can see, the result is made of two elements (ID and sentence). How can I read/manipulate in the code provided by choroba only the second element "sentence", preserving at the end of the sorting operation the same structure ID/sentence?

        1. use ORDER BY in SQL to have the data delivered to perl in the expected order
        2. Schwartzian transform

        Alexander

        --
        Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)