Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: How can I access object data in a user defined sort cmp function?

by geistberg (Novice)
on Jan 29, 2015 at 19:18 UTC ( #1114962=note: print w/replies, xml ) Need Help??


in reply to How can I access object data in a user defined sort cmp function?

The <=> can dig into objects and hashes, so you can use something like $a->key->{'other'} <=> $b->key->{'other'}. Proof of concept:
#/usr/bin/perl use warnings; use strict; use Data::Debug; my @things; push @things, Thing->new() for (1..10); debug @things; my @sorted = sort { $a->key->{'other'} <=> $b->key->{'other'} } @thing +s; debug @sorted; package Thing; sub new { return bless { key => { other => int(rand(42))} }, 'Thing'; +} sub key { return shift->{'key'}; } 1;
I hope that is helpful :)
  • Comment on Re: How can I access object data in a user defined sort cmp function?
  • Download Code

Replies are listed 'Best First'.
Re^2: How can I access object data in a user defined sort cmp function?
by tkguifan (Scribe) on Jan 29, 2015 at 19:37 UTC
    This is not the same thing. You are sorting the objects themselves rather than a hash stored within an object. This is a cheat because now $a and $b are object references, so they speak for themselves. If $a and $b are simply keys of a hash, the sort function has no clue to what object they belong. However it is true, as others pointed out, that if I write the compare function in-line instead of a separate function, the in-line code sees the variables of the sub ( including the $self with which it was called ), so it has access to the object.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2022-01-21 17:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (59 votes). Check out past polls.

    Notices?