CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Print order hash

 



mmcw
User

Aug 11, 2000, 11:58 PM

Post #1 of 2 (327 views)
Print order hash Can't Post

Hello,

I have a problem with printing of a hash.

I have the following hash:

%order_forms = (
"Shipping Method" => "",
"Shipping Form" => "On",
"Billing Form" => "On",
"Credit Form" => "On",
"EMail Form" => "On",
"Comments Form" => "On"
);

I use this little sctipt code to print the hash:

foreach $temp (%order_forms) {
print "Value: $temp<br>";
}

The result will be:

Value: Comments Form
Value: On
Value: Shipping Method
Value:
Value: EMail Form
Value: On
Value: Billing Form
Value: On
Value: Shipping Form
Value: On
Value: Credit Form
Value: On

The strange thing happens that the order has been changed!!

I want to keep the order as in the hash!!

I want the result to be:

Value: Shipping Method
Value:
Value: Shipping Form
Value: On
Value: Billing Form
Value: On
Value: Credit Form
Value: On
Value: EMail Form
Value: On
Value: Comments Form
Value: On

What to be done???


Kanji
User

Aug 12, 2000, 5:54 AM

Post #2 of 2 (327 views)
Re: Print order hash [In reply to] Can't Post

This was already addressed in this forum but a few days ago: hashes aren't ordered like you think, so if you want a specific order, you're responsible for making it happen.

Anyhoo, to that end, you can create an array of keys in the order you want, and iterate over your results that way ...

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

@order = ( "Shipping Method", "Shipping Form", "..." );
foreach $key ( @order ) {
print "VALUE: $key\n";
print "VALUE: $order_forms{ $key }\n";
}</pre><HR></BLOCKQUOTE>

... or use multi-dimensional constructs, like an array of hashes or an array of arrays (since arrays are always in the same order you put them in).

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

@order_forms = (
[ "Shipping Method" => "" ],
[ "Shipping Form" => "On" ],
[ "..." => "..." ],
);

foreach $pair ( @order_forms ) {
print "VALUE: $pair->[0]\n"; # ie, Shipping Form
print "VALUE: $pair->[1]\n"; # ie, On
}</pre><HR></BLOCKQUOTE>

... or make sure your keys are in sortable order ...

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

%order_forms = (
"a Shipping Method" => "",
"b Shipping Form" => "On",
"c ..." => "...",
);
foreach $key ( sort keys %order_forms ) {
( my $name = $key ) =~ s/^. //;
print "VALUE: $name\n";
print "VALUE: $order_forms{ $key }\n";
}</pre><HR></BLOCKQUOTE>

[This message has been edited by Kanji (edited 08-12-2000).]

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives