in reply to Re: Print hash value even if it's zero
in thread Print hash value even if it's zero

OK, here you go!
open OUT, ">>$outfile" or die "Can't open $outfile for writing: $!\n"; print_hash_cvs(%jobstats); close OUT; exit(0); sub print_hash_cvs { my (%hash) = @_; my ( $key, $val ); foreach $key ( keys %hash ) { $val = $hash{$key}; print OUT "$val|"; } print OUT "$yesterday|$today\n"; }

Replies are listed 'Best First'.
Re: Re: Re: Print hash value even if it's zero
by dws (Chancellor) on Nov 18, 2002 at 20:49 UTC
    I don't see what this code isn't printing 0 (zero), but I do note that print_hash_cvs is printing values in essentially random order. Hashes don't guarantee key order. Most of the time, if you set up a hash the way you do, you'll get back keys in the same order, but it's not a good idea to assume that. If some other script is going to assume field order, then you're much better off being explicit about which fields you're writing.

    Something like:

    my @fields = qw(total_jobs ... retried_jobs); ... foreach my $key ( @fields ) { my $val = $hash{$key}; print OUT "$val|"; }
    is a safer.

      I'm using "Tie::IxHash", which will allow me to retrieve hash elements in the order of insertion.

      See Camel: pg. 139