Hello, I'm new here

I could need some help to improve one of my subs, I've done some "google" but apparently to no awail.

The sub needs to make a PNG-file based on contents in a hash specified by one input used both as the hash key and the resulting filename.

My question is however if there's a more efficient way to write a hex string as binary to a file? Feedback appreciated.

sub writeAnImage { my $hashCode = $_[0]; my %pngData = ( 'blank', '89504e470d0a1a0a0000000d49484452000000320000005a0803000000 +cd46f5b400000003504c5445efefefec97ba8d0000001b494441545885edc1010d000 +000c2a0f74f6d0f0714000000003f0611ee00013060c47e0000000049454e44ae4260 +82' ); my $dataString = ""; my $twoHex = ""; my $dataLength = 0; my $byteCounter = 0; # if ($hashCode) { if ($pngData{$hashCode}) { $dataString = $pngData{$hashCode}; $dataLength = length($dataString); open(MyPNG, ">$hashCode") or die("Write Error: $hashCode"); binmode(MyPNG); for ($byteCounter = 0; $byteCounter <= $dataLength; $byteCounter + += 2) { $twoHex = substr($dataString, $byteCounter, 2); print MyPNG chr(hex($twoHex)); } close(MyPNG); } else { print "No such code in the hash ($hashCode)\n"; } } else { print "No code specified\n"; } }

In reply to What is the best method to print hex string in bin-file? by cosmofield

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.