http://qs321.pair.com?node_id=1114767


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

As I understand your question, you have a hash reference, and you want to sort some keys inside the hash. In your example, you want to get 'item1' and 'item2', in that order.

If that is so, the solution is simple:

@keys = sort keys %{ $self->{hash_ref} };

There is no sort routine, because by default sort() sorts things in ascending order. $self->{hash_ref} is a reference to the hash whose keys you want sorted, %{ $self->{hash_ref} } is the hash itself, and keys %{ $self->{hash_ref} } is the list of keys to be sorted.

If you need a sort routine in the above, the $a and $b would be the individual keys; so if you wanted a reverse sort you would do

@keys = sort { $b cmp $a } keys %{ $self->{hash_ref} };

Note that I did not use the word "object" because your example does not contain an object in the Perl sense of the word. Your '$self' would be an object if it had been blessed; that is, if the code to construct it had been

$self = bless { hash_ref=>{item1=>'value1',item2=>'value2'} }, 'Some::NameSpace';

The code to sort the keys would not change, though depending on where that code lives, it might violate encapsulation. On the other hand, Perl's encapsulation model has been described more as "I do not make myself at home in your living room because I was not invited," rather than "I do not make myself at home in your living room because you have a shotgun."

As for "the $self of an object", there is nothing magic about $self; it is simply a variable like any other. You could use $this, or $me, or anything. To access the internals of an object, you simply need a reference to the object, and it does not matter what that reference is called.