Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

what's wrong with this code :

actually two questions :

1) why don't the $a,$b values of the SORT routine
print ?

2) what is wrong with the sort routine?
it doesn't sort; (rearrange the list)
package netFetObj; sub fetSort { print " ######### A = $a \n"; print " ######### B = $b \n"; my $ftA = $a->{"fet"}; my $ftB = $b->{"fet"}; $fetType->{$ftA} <=> $fetType->{$ftB} }
where fetType is updated
whenever the appropriate object method is invoked
package something_else; foreach my $fetOBJ ( sort { &netFetObj::fetSort } @{ $OBJ->{"fets" +} } ) { buildFet($FH,$fetOBJ,$OPT); }
and the LIST to sort is a list of netFetObjs.

Edited by planetscape - removed pre tags, added code tags and rudimentary formatting

( keep:0 edit:6 reap:0 )

Replies are listed 'Best First'.
Re: sorting objects
by rhesa (Vicar) on Jun 23, 2006 at 01:16 UTC
    Two notes:
    1. sort can take a subname, so a simple sort netFetObj::fetSort @list looks cleaner than your construct.
    2. if you don't use a prototyped sort sub, $a and $b are globals in package something_else. That means you should refer to them as $something_else::a and $something_else::b inside fetSort.
    To summarize:
    package netFetObj; sub fetSort { print " ######### A = $something_else::a \n"; print " ######### B = $something_else::b \n"; my $ftA = $something_else::a->{"fet"}; my $ftB = $something_else::b->{"fet"}; $fetType->{$ftA} <=> $fetType->{$ftB} } package something_else; foreach my $fetOBJ ( sort netFetObj::fetSort @{ $OBJ->{"fets"} } ) + { buildFet($FH,$fetOBJ,$OPT); }

      doh! i feel really silly. of course, the variables would be in the namespace of the caller.

      i had tried various combinations of & and $ on the sort routine. little did i realize that NO symbols are needed!

      yes, i need to use a prototyped sort sub as many other packages will call this.

      BTW, i also changed the hash access to a method

      my $ftA = $_[0]->fet(); my $ftB = $_[1]->fet();

      this looks cleaner too!

      thanks again...

      Formatting and code tags added by GrandFather

Re: sorting objects
by ikegami (Patriarch) on Jun 23, 2006 at 01:16 UTC

    sort is placing the values in $something_else::a and $something_else::b since it was called from package something_else. The workaround is to tell sort to pass the values as parameters by using the ($$) prototype:

    sub fetSort($$) { # Prototype necessary. my $ftA = $_[0]->{"fet"}; my $ftB = $_[1]->{"fet"}; $fetType->{$ftA} <=> $fetType->{$ftB} } package something_else; sort netFetObj::fetSort @{ $OBJ->{"fets"} }

    This negatively affects performance, according to the docs.

    In the future, please use <c>...</c> around your code rather than (an unclosed) <pre>...</pre>, as per the Monestary Guidelines. A janitor will have to fix it for you.