I am trying to convert a numbers in a file I have a line: $line2 = printf ("%#x", $line); $line for example is 55473 $line2 ends up containing a 1 not the 0xd8b1 I was expecting and when I run program I see the 0xd8b1 written to the screen, how do I get $line2 to have the 0xd8b1 value ?

Thanks a million to all for the sprintf answer and the other comments.

Getting printf to work was harder than sprintf, however was very educational.

I looked at Prototypes in perlsub and Far More than Everything You've Ever Wanted to Know about Prototypes in Perl -- by Tom Christiansen, I also looked at "perl in a nutshell" and "Perl 5 by Example" and didn't see what to do. Finally after a number of changes and web searches the following seems to work without the warnings " called too early to check prototype at convert4.pl and "use of unitialized value". I am assuming this is correctly coded?

documentation on prototypes is poor for a beginner (or at least me).

#!/usr/bin/perl # convert4.pl use warnings; use strict; use Carp (); local $SIG{__WARN__} = \&Carp::cluck; sub capture_stdout($) { my($v); my $line = shift; local *STDOUT; open(STDOUT, '>', \$v); printf ("%#x", $line); return $v; } open(MYINPUTFILE, "<test.dat"); open(MYOUTPUTFILE, ">hex.dat"); while(<MYINPUTFILE>) { my($line) = $_; my $line2 ; chomp($line); $line2 = capture_stdout($line) ; print MYOUTPUTFILE "$line2\n"; } close(MYINPUTFILE); close(MYOUTPUTFILE);

In reply to getting wrong value by ggrise

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.