in reply to Help: Constructors and all things OO.
This works OK. I've dropped in the sort for you to show you how you do it. $a and $b are the elements from the @array that we are sorting. In this case they are hash refs so we deref them to get the values we want to do our (numeric) sort on. You use 'cmp' rather than the spaceship '<=>' if you want a alphabetic sort. Note that reversing $a and $b reverses the sort order.
#!/usr/bin/perl -w my $obj = iXML::TheConstruct->new(); # add some stuff for testing my $html = "A"; for $index( reverse 0..10) { $obj->add($html,$index); $html++; } # print it print "Here is our object\n", $obj->output; # do some sorts $obj->sort_asc; print "\n\nSort ascending\n", $obj->output; $obj->sort_dsc; print "\n\nSort descending\n", $obj->output; exit; ########### here is the module so we need no use ########### ############################################################ package iXML::TheConstruct; $VERSION = 0.01; use strict; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = []; bless($self, $class); return $self; } sub add { my ($_self, $_obj_html, $_ind) = @_; my $_obj_hash = { OBJ_HTML => $_obj_html, OBJ_IND => $_ind}; push @{$_self}, $_obj_hash; } sub sort_asc { my $_self = shift || die "No object to sort!"; @$_self = sort { $a->{'OBJ_IND'} <=> $b->{'OBJ_IND'} } @$_self; } sub sort_dsc { my $_self = shift || die "No object to sort!"; @$_self = sort { $b->{'OBJ_IND'} <=> $a->{'OBJ_IND'} } @$_self; } sub output { my ($_self) = @_; my $_html_data; foreach my $_obj ( @{$_self} ) { my $index = $_obj->{'OBJ_IND'}; my $html = $_obj->{'OBJ_HTML'}; $_html_data .= "$index => $html\n"; } return $_html_data; } 1;
cheers
tachyon
s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Help: Constructors and all things OO.
by IOrdy (Friar) on Aug 28, 2001 at 17:49 UTC | |
by tachyon (Chancellor) on Aug 28, 2001 at 18:33 UTC | |
by IOrdy (Friar) on Aug 28, 2001 at 18:42 UTC |