Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Creative use of pack/unpack

by Eureka_sg (Monk)
on Apr 17, 2001 at 21:00 UTC ( [id://73250]=perlquestion: print w/replies, xml ) Need Help??

Eureka_sg has asked for the wisdom of the Perl Monks concerning the following question:

I'm pretty new to the usage of pack/unpack. Other than the obvious usage of converting between bin/hex/char/etc formats, would anyone like to share how they might be useful in less obvious ways?

Replies are listed 'Best First'.
(tye)Re: Creative use of pack/unpack
by tye (Sage) on Apr 17, 2001 at 23:38 UTC

    Here is the most creative use of pack I've come up with:

    #!/usr/bin/perl -w use strict; my $password= "Not really"; hide( $password, "none of your business" ); print "password=($password), hide=(",hide($password),")\n"; $password= "No!"; print "password=($password), hide=(",hide($password),")\n"; # Prints: #password=(Not really), hide=(none of your business) #password=(No!), hide=(none of your business)
    But the rest of the code (that uses pack and unpack) is the spoiler so I'll obscure it:

    sub hide { my( $new )= 1<@_ ? pop : undef; my $secret; my( $p2, $rc, $f )= unpack "LLL", unpack "P12", pack "L", \$_[0]; if( 5 == unpack "C", pack "V", $f ) { my( $pv, $cur, $siz, $iv )= unpack "L4", unpack "P16", pack "L", $p2; $secret= unpack "P$iv", pack "L", $pv-$iv; } if( defined $new ) { $_[0]= $new . $_[0]; substr( $_[0], 0, length($new) )= ""; } return $secret; }

    This allows you to store secret messages in scalars where no Perl code can find them (other than using pack/unpack or resorting to, for example, C code).

    (updated)

            - tye (but my friends call me "Tye")
Re: Creative use of pack/unpack
by princepawn (Parson) on Apr 17, 2001 at 21:09 UTC
    As discussed in this node you can use it to implement fixed-width parsing of data.

    Also, I would imagine it would be good for making translation between host and network byte order on little Endian architectures.

Re: Creative use of pack/unpack
by arhuman (Vicar) on Apr 17, 2001 at 21:43 UTC
    As I said in one of my previous nodes, if you do some sorting this article definitly shows a good use for pack...


    "Only Bad Coders Badly Code In Perl" (OBC2IP)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://73250]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-23 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found