in reply to dividing a hash by sets of $num

Step 1: Find some way to get a list of hash keys that has a stable order. Hashes are unordered so theres no way to know where any 6 items happen to lie in correlation to each other. My first thought would be just sorting the keys but other methods will work.

Step 2: Create a param that stores what page you're on and pass it in your "next" link. Example, foobar.com?page=3. Page is your "counter variable".

Step 3: Multiply your counter variable by the number of items you want to display per page as an indice in to your array.

Step 4: Use your indices to extract a list of keys from your array of keys, then use this list to extract a list of elements from your hash.

Sample code:
use CGI; my $c = CGI->new(); my %hash = qw/data and stuff/; #however you fill the hash #Step 1 my @keys = sort keys %hash; # this should maintain the same order, ass +uming hash doesn't change #Step 2 my $counter = $c->param('page'); #step 3 my $begin = $counter * $items_per_page; my $end = $begin + $items_per_page; #step 4 print @hash{ @keys[ $begin..$end ] }; #deep voodoo

Replies are listed 'Best First'.
Re: Re: dividing a hash by sets of $num
by Anonymous Monk on Mar 14, 2004 at 15:24 UTC
    I thank you for your wisdom but I hope you don't mind me asking you a question or two about your example.

    By param do you mean url_param for the page? I thought if it was given by the browser, it had to be url_param. I've never really tried it the way you do everything else..perhaps I should.

    We have 13 keys.. --page 2-- $begin would be (2) * 6 = 12 $end would be 12 + 6 = 18. Page two would display items 12-18 which would actually be 7 numbersm +right?
      1) By param I meant a key=value paramater passed to your script via CGI (I'm assuming this is cgi). These come in two forms, a "post" type, and your script reads those via STDIN and "get" types, which come after the question mark in the url. CGI.pm decodes both of these and gives you the value(s) with the method "param". Note that if there are any "posted" paramaters, CGI.pm will only return those when you call param, it will ignore any params in the "get" request.
      #incoming url = script.cgi?foo=bar&baz=qux my $c = CGI->new(); print $c->param('foo'); #prints bar print $c->param('baz'); #prints qux
      2) Uh, I guess. Thats an implementation issue, doesn't really matter.