Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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

by choroba (Cardinal)
on Jan 28, 2015 at 14:28 UTC ( [id://1114752]=note: print w/replies, xml ) Need Help??


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

You can create a closure for the object:
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $self = { hash_ref => { item1 => 12, item2 => 9, }, }; print Dumper(sort_hash_ref_keys_by_value($self)); sub sort_hash_ref_keys_by_value { my $self = shift; my $by_value = sub { $self->{hash_ref}->{$a} <=> $self->{hash_ref}->{$b} }; return sort $by_value keys %{ $self->{hash_ref} }; }
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
  • 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 sundialsvc4 (Abbot) on Jan 28, 2015 at 23:38 UTC

    “Schweee-e-ee-t!”   An extremely elegant solution.

    ++   ++   ++   ...

    And, just for completeness, just for the “technically confused curious” passers-by (however many years from now ...) about “what in the heck a ‘closure’ is,” and with no attempt to steal anyone’s thunder:

    A closure is voodoo an advanced technique that Perl makes very easy.   The local variable named $by_value is made to contain a reference to an anonymous sub which was created within a block of code in which a local variable named $self was “visible” to it, and in which it was known that this $self would continue to exist (with its then-present value) for the duration over which it will be needed.   (Namely:   “the lifetime of sub sort_hash_ref_keys_by_value.”)   This anonymous sub ... a “closure” ... will, rather magically, be able to “see” $self too, and can therefore refer to it in addition to $a and $b.   Each time the sort verb invokes this anonymous function, that function will magically be able to “see” $self, as though the sort verb, itself, were also located in the same block of source-code in which the closure-sub is defined.   The next best thing to being in two places at one time.

    Masterful.   Brilliant.

Re^2: How can I access object data in a user defined sort cmp function?
by soonix (Canon) on Jan 29, 2015 at 10:04 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-19 03:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found