in reply to Using serialized data structure to change hash key

Hello docdurdee,

The problem with this approach is that SOMEKEY might also appear elsewhere in the hash: as a substring of another key, or as a value. The first case can be tackled by adding word boundaries to the regex: $yaml =~ s{\bSOMEKEY\b}{SomeKey}. But I don’t see any obvious solution to the second case:

#! perl use strict; use warnings; use Data::Dump; use YAML::XS; my $hash = { Fred => 'Wilma', Frederick => 'Mary', Barney => 'Fred' }; my $yaml = Dump $hash; $yaml =~ s/\bFred\b/FRED/; $hash = Load $yaml; dd $hash;

The output I (happen to?) get:

0:26 >perl 1186_SoPW.pl { Barney => "FRED", Fred => "Wilma", Frederick => "Mary" } 0:30 >

Of course, you can add a /g modifier to the substitution, but you’ll still get the value changed as well, when you don’t want it to be. :-(

Update: On second thought, I think this should work for most cases:

$yaml =~ s/(?<=\n)Fred(?=:)/FRED/g;

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Using serialized data structure to change hash key
by docdurdee (Scribe) on Mar 18, 2015 at 16:55 UTC
    Thanks Athanasius! The last two sentences of the meditation were intended to express that care would be needed to actually us this trick. Thank you for providing the potential pitfalls. The described trick has made my life much easier more than once when working with some data stored in a hash, but I was very familiar with the data (even if the data structure had gotten a little out of hand).