Well, before we get to your question, there are a few things that need to be cleared up. First, it's good to see you trying out advanced techniques and getting more tools in your box, but you do have a few issues.

Your first data structure has parentheses around it. That makes it a comma expression which, when evaluated in list context, will return a list. In scalar context, its value is whatever the last item evaluates to. You only have one item, so your scalar gets the array ref and your code works, but you should avoid doing things like this unless you're positive that this is what you need. Drop the parentheses.

The Schwartzian is overkill. A Schwartzian transform is great if you have an expensive step to extract the data and put it in a sortable format. You do not have such a step. Your Schwartzian reduces to this:

my @sorted = sort { $a->{num} cmp $b->{ num } } @$data;

If it makes you feel better, I was caught by the same issue. See Sort on Boredom :)

Here's how I shortened your code:

#!/usr/local/bin/perl -w use strict; my $data = [ { num => 'OF1234', title => 'title OF1234', }, { num => 'AF1234', title => 'title AF1234', }, { num => 'AF1234', title => 'title AF1234', }, ]; my %saw; my @sorted = grep { ! $saw{$_->{num}}++ } sort { $a->{num} cmp $b->{ num } } @$data; print join ', ', map { $_->{num} } @sorted;

Hope that helps.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.


In reply to (Ovid) Re: Can Schwartzian transform be modified to sort an arrayref uniquely? by Ovid
in thread Can Schwartzian transform be modified to sort an arrayref uniquely? by corporate_gadfly

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.