There is one slight disadvantage to merlyn's solution in the initial reply: the strings you are converting into hex numerics will probably include "\n" characters, which of course are "\x0a" -- but  unpack "H*", "\n" will produce just "a" (no leading zero), and based on your reply to merlyn, this is not what you want.

You seem to want output that consistently shows two hex digits per ASCII character, with leading zero where needed.

So use sprintf (and use ALL_CAPS for a file handle name, or else use a lexically scoped scalar variable, instead of a lower-case bare word; and don't bother holding the whole file content in an array):

use strict; open( IN, "file.txt" ) or die "file.txt: $!"; open( OUT, "out.txt" ) or die "out.txt: $!"; # or: open( my $in, "file.txt") ... while (<IN>) { # or: while (<$in> ...) $_ = join "", map { sprintf("%2.2x",ord($_)) } split //; print OUT $_, $/; }
If "map" is foreign to you, you can use a loop like the following, but you should learn to like map because in this kind of case it'll probably run faster than the for loop):
my $outstr = ""; $outstr .= sprintf("%2.2x",ord($_)) for (split //); print $outstr, $/;
For that matter, when doing a simple "in->out" text filter like this, I prefer not to use open at all -- just  while (<>) { ... print; } -- then provide the input file name as a command line arg, and redirect STDOUT to some other file.

In reply to Re: Converting ASCII to Hex by graff
in thread Converting ASCII to Hex by Anonymous Monk

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.