开发者

serialize/deserialize & modify data

I have a perl script that pulls serialized php data from a database, unserializes it, modifies the data, then serializes it again. What I would like to do is modify the name & pet fields (as indicated below) but can't figure out how 开发者_StackOverflow中文版to access individual fields to modify them:

use PHP::Serialization qw(serialize unserialize);
use Data::Dumper qw(Dumper); 

###blah, blah, blah
while ( @a = $sth->fetchrow() ){
my $hashref = unserialize( $a[0] );
print Dumper($hashref); 
}
OUTPUT:
$VAR1 = [
      bless( {
               'name' => 'Fred', # I want this to be Dave
               'pet' => 'Cat',  # I want this to be Dog
               'date' => '1977'
             }, 'PHP::Serialization::Object::stdClass' ),
      bless( {
              'name' => 'Mary', # I want this to be Jane
               'pet' => 'Worm', # I want this to be Pig
               'date' => '1977'
             }, 'PHP::Serialization::Object::stdClass' )
    ];

UPDATE: Thx to Hugmeir, I have the following, which seems to work. Is this the best way to change the 'name' if I don't know the index number?

for my $hashref (@{$array_ref}) {

        if ( $hashref->{name} =~ /Mary/ ){
          $hashref->{name} = 'Jane'; 
         }

}


For starters, that's not a hashref - It's an arrayref that holds two elements, each a hashref*. This breaks PHP::Serialization's encapsulation, but should do the trick:

my $array_ref = unserialize( $a[0] );

for my $hashref (@{$array_ref}) {
    @{$hashref}{qw(name pet)} = ('New name', 'New Pet');
    #Or $hashref->{name} = 'new name'; If you don't like slices.
}

EDIT: If you only wanted to modify, say, the first element, you could do

$array_ref->[0]->{name} = 'etc';

*Technically two hashrefs blessed to PHP::Serialization objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜