Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: JSON saving regex?

by GrandFather (Sage)
on Jan 27, 2012 at 02:32 UTC ( #950251=note: print w/replies, xml ) Need Help??


in reply to JSON saving regex?

In essence you can't do that. $test contains a Perl regular expression object and JSON doesn't have an out-of-the-box way to deal with them.

If you don't need to round trip the data, but are providing it for consumption elsewhere the allow_blessed function will suppresses the error, insert a 'null', and carry on:

use strict; use warnings; use JSON qw(); my $test = {regex => qr/^[\w\@\.]+$/, str => "this is a string"}; my $json = JSON->new(); $json->allow_blessed(1); print $json->encode($test);

Prints:

{"str":"this is a string","regex":null}

Update: and if you do want to round trip it with another Perl script then think about using YAML instead:

use strict; use warnings; use YAML qw(); my $test = {regex => qr/\w+\W+(\w+)/, str => "this is a string"}; my $yamlStr = YAML::Dump($test); print "YAML: $yamlStr\n"; my $andBack = YAML::Load ($yamlStr); my ($secondWord) = $andBack->{str} =~ $andBack->{regex}; print "Second word is: $secondWord\n";

Prints:

YAML: --- regex: !!perl/regexp (?-xism:\w+\W+(\w+)) str: this is a string Second word is: is
True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://950251]
help
Chatterbox?
[Corion]: choroba: Yes, but the longer I thought about efficient hashes mapping the event type back to their callbacks, and how to keep them in sync, the more I thought that all that optimization might just not be worth it, even if it's horribly inelegant
[Lady_Aleena]: My biggest problem with hashes at the moment is one with 2,501 keys.
[choroba]: how many event types are there?
[Corion]: Also I found that I can't conveniently weaken an array slot, which also is inconvenient, as I want my one-shots to disappear if the caller discards them
[Corion]: choroba: Currently two or three that my program handles (WWW::Mechanize:: Chrome), but there might be more that become interesting
[Corion]: But I don't expect more than 100 to be active at the same time, so I'm not really sure if there is a not-too-fancy data structure that is maintained with few lines of code where the performance is better than the linear scan ;)
[Corion]: But I should do a mock-up program so that others can see what I'm talking about ;)
[robby_dobby]: Corion: I hope you know all too well that passing around "fancy" datastructures is a recipe for disaster :-)
[robby_dobby]: As in, it's-too-fancy- that-it-will-be- messy-to-handle
[choroba]: bit vectors as keys?

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (13)
As of 2017-05-29 07:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?