Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Printing a int as hex

by Dr Manhattan (Beadle)
on Sep 09, 2013 at 18:54 UTC ( #1053073=perlquestion: print w/ replies, xml ) Need Help??
Dr Manhattan has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks

I'm having some trouble in printing a hash value (normal integer) as a hexadecimal value. This value has to be small caps, and 2 digits long

When I do a simple script like this to test the code:

my %hash; $hash{a}{key} = 7; $hash{b}{key} = 10; $hash{c}{key} = 11; $hash{d}{key} = 12; $hash{e}{key} = 13; foreach my $x (keys %hash) { printf "%02x\n", $hash{$x}{key}; }

-it works perfectly fine

In the example code I try to print a hash value(which is a normal integer) as a hex value. I am using the printf and hex functions, but somehow I get stuck. For instance if my hash value is 10, I want the output to be 0a. All I get back though is normal ints.

Thanks in advance for any help, much appreciated


But when I try to implement that in my real script, it does not work

foreach my $id (sort keys %hash) { printf Out "%02x\n", $hash{$id}{"counter"}; }

Somehow it filters out all values larger than 10 from my output. This is strange because the code is the same...

Replies are listed 'Best First'.
Re: Printing a int as hex
by toolic (Bishop) on Sep 09, 2013 at 19:00 UTC
    Since your hash values are decimal values (not hex strings), there is no need to use hex:
    use warnings; use strict; my %hash = (x => 10); foreach my $x (keys %hash) { printf "%02x\n", $hash{$x}; } __END__ 0a
Re: Printing a int as hex
by McA (Priest) on Sep 09, 2013 at 18:59 UTC
Re: Printing a int as hex
by Laurent_R (Abbot) on Sep 09, 2013 at 21:14 UTC

    Your code is not doing anything with the contents of hexfile.txt, but is only reading the contents of %hash, in which there is only one key-value pair. I strongly suspect that this is not really what you were intended, but I cannot know for sure, because you did not say what you wanted to do.

Re: Printing a int as hex
by marinersk (Curate) on Sep 09, 2013 at 22:17 UTC
    I don't see quite enough information to answer the question.

    Could you replace your foreach loop with this and post the results?

    foreach my $id (sort keys %hash) { print "\$hash{$id} = '$hash{$id}'\n"; my $counterValue = $hash{$id}{"counter"}; print " -> counter = '$counterValue'\n"; }


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1053073]
Approved by toolic
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2016-06-26 06:56 GMT
Find Nodes?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...

    Results (328 votes). Check out past polls.