-4

I confused with pack and unpack while writing a Perl script. What is the difference between between pack and unpack in Perl (explain with a simple example)?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • pack packs, unpack unpacks its like printf and scanf – Noam Rathaus Dec 17 '13 at 06:32
  • 6
    could you read the docs and mention what exactly it is you do not understand? – gideon Dec 17 '13 at 06:33
  • how to use this pack and unpack.I'm confused with both of them.can you explain with one simple examples.? – user3098497 Dec 17 '13 at 06:35
  • 3
    At the command prompt, type "perldoc -f pack", "perldoc -f unpack", and "perldoc perlpacktut". Those documents present what pack and unpack do, and how they differ. If you're still confused, you would then be able to come up with a more specific question. – DavidO Dec 17 '13 at 06:42
  • @user3098497 - you really are going to have to read some documentation yourself and *try some code*. Otherwise this is going to be a slow and painful learning process for you. – Richard Huxton Dec 17 '13 at 07:07
  • 3
    The difference between `pack` and `unpack` should be pretty obvious from their names. Imagine you have lots of items of clothing and a suitcase. When you pack the suitcase, you take the individual items of clothing and put them into the suitcase. When you unpack the suitcase you take the items of clothing out of it. Similarly, `pack` takes a list of data items and packs them into a single piece of data and `unpack` takes a single piece of data and unpacks the individual data items stored in it. You probably need to be clearer about what you don't understand. – Dave Cross Dec 17 '13 at 13:48
  • Have your read the [pack tutorial](http://perldoc.perl.org/perlpacktut.html)? – Michael Carman Dec 17 '13 at 14:33

2 Answers2

4

Do you understand the difference between split and join? unpack is a bit like split (it takes a string and produces a list of values) and pack is a bit like join (it takes a list of values and produces a string.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97
3

pack takes a list of values and converts it into a string using the rules given by the template.

unpack takes a string and expands it out to a list of values using the rules given by the template.

$ perl -E 'say for unpack "H2H2", "56"'
35
36

$ perl -E 'say pack "H2H2", 35, 36'
56
DavidO
  • 13,812
  • 3
  • 38
  • 66