Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Unserialize String to hash

by santosh_vjit (Novice)
on Jun 30, 2010 at 12:27 UTC ( [id://847314]=perlquestion: print w/replies, xml ) Need Help??

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

A php string is serialized and stored in database i need to unserialize it and store it in hash can anyone please me in this problem. a:1:{s:4:"Name";s:5:"sandy";s:5:"sport";s:7:"cricket";}

Replies are listed 'Best First'.
Re: Unserialize String to hash
by jethro (Monsignor) on Jun 30, 2010 at 13:02 UTC
Re: Unserialize String to hash
by Taulmarill (Deacon) on Jun 30, 2010 at 12:56 UTC

    There is a module for that: PHP::Serialization

Re: Unserialize String to hash
by Marshall (Canon) on Jun 30, 2010 at 13:13 UTC
    Lots of ways to do this task. In Perl, the field width stuff is not important. Below is one way. A "match global" regex is used to extract the pairs and then a while loop puts them into a hash.
    #!/usr/bin/perl -w use strict; use Data::Dumper; my $x = 'a:1:{s:4:"Name";s:5:"sandy";s:5:"sport";s:7:"cricket";}'; my %hash; my ($key,$value); my @tokens = $x =~ m/"(.*?)"/g; $hash{$key}= $value while (($key, $value)= splice(@tokens,0,2)); print Dumper(\%hash); __END__ prints $VAR1 = { 'sport' => 'cricket', 'Name' => 'sandy' };
Re: Unserialize String to hash
by sierpinski (Chaplain) on Jun 30, 2010 at 12:49 UTC
    What should the key-value pairs be? Is 's' included? I'm assuming that you want something like this:
    %a1 = ( 'Name'=>'sandy', 'sport'=>'cricket', );
    Is that basically what your goal is? Is there significance to the 's' characters in the string? Once it's known what you're looking for, one of the saintly regular expression masters here (sadly I'm still a greenhorn) could probably make quick work of it.

    I should also ask, is that just a sample of data, or will it always be in exactly that format?

Log In?
Username:
Password:

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

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

    No recent polls found