Perl Quickie

Eric Eisenhart eric at eisenhart.com
Sat Nov 6 13:45:26 CST 1999


On Mon, Apr 05, 1999 at 11:15:43AM -0700, Jay Di Silvestri wrote:
> I think that the answer is in the pack function, but I don't work with
> hex numbers enough to get working code.   I'm forwarding this to the
> group list.  Perhaps someone will know.  I was surprised to find out
> that print "\x23", will print that character, but $foo="23"; print
> "\x${foo}"  will not yield the same result.
[snip]
> William Smith wrote:
[snip]
> > I want to create a file and fill it with 256 bytes 0x00 -> 0xff.
> > Everything I try writes text representations of the numbers.
[snip]

The easiest answer is indeed the pack function.  Perl has explicit
conversion between numeric and string types, such that any number is
equivalent to its string representation (sorta).

Here's a simple snippet of code that does what you want:
for (0x1 .. 0xff) {   # Same as 1 .. 255, just clearer for this purpose
    print( pack( "c", $_ ) );
}

And, of course, the Perl motto is TMTOWTDI, so:
for $i (0x1 .. 0xff) {
    printf("%c", $i);
}

(It's pretty much the same printf() as C has.  In fact, until very recently
Perl just used the printf provided in C on that system.  Perl now uses its
own printf because differences between printf on different systems were
causing compatibility problems for some code.
-- 
    Eric Eisenhart   Freedom is slavery.      http://eric.eisenhart.com/
 ^  ICQ#: 48217244   Ignorance is strength.   eric-dot-sig at eisenhart.com
/e\ Perl&SQL Coder   War is peace.            IRC Nicks: Falsch Freiheit
---                        -- George Orwell
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.pm.org/archives/santa-rosa-pm/attachments/19991106/bff90915/attachment.bin


More information about the Santa-rosa-pm mailing list