Another way to do this?

T

Trebor A. Rude

In an effort learn Perl, I was converting some of my smaller C++ programs to
Perl scripts. I had one program which printed out the bytes of an integer
as characters (so 0x616263 would be "abc"). I've got a Perl solution, but
for some reason it seems unnecessarily complicated. Is there a better way
to accomplish the same thing as the script below? I keep thinking that pack
or unpack can do it, but darned if I can figure out how.

#!/usr/bin/perl -w

use strict;

for (@ARGV)
{
$_ = oct if /^0/;
my @bytes;
do { unshift @bytes, $_ & 0xFF; } while (($_ >>= 8) > 0);
print chr for @bytes;
print "\n";
}
 
T

Tassilo v. Parseval

Also sprach Trebor A. Rude:
In an effort learn Perl, I was converting some of my smaller C++ programs to
Perl scripts. I had one program which printed out the bytes of an integer
as characters (so 0x616263 would be "abc"). I've got a Perl solution, but
for some reason it seems unnecessarily complicated. Is there a better way
to accomplish the same thing as the script below? I keep thinking that pack
or unpack can do it, but darned if I can figure out how.

Yes, pack() and unpack() are quite suitable for that.
#!/usr/bin/perl -w

use strict;

for (@ARGV)
{
$_ = oct if /^0/;
my @bytes;
do { unshift @bytes, $_ & 0xFF; } while (($_ >>= 8) > 0);
print chr for @bytes;
print "\n";
}

In Perl this can be condensed into a one-liner:

perl -le 'print unpack "A*", pack "H*", $_ for @ARGV' 0x616263 0x626364
abc
bcd

Or as a real script:

print ((unpack "A*", pack "H*", $_), "\n") for @ARGV;

See 'perldoc -f pack'.

Tassilo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,149
Messages
2,570,841
Members
47,388
Latest member
EarthaGilm

Latest Threads

Top