http://qs321.pair.com?node_id=1198766


in reply to Freezing a regular expression qr()

I can't really tell if what you want is sane, but I found the documentation of JSON::XS to be fairly explicit. If the convert_blessed option is set and an object has a TO_JSON method, that method will be called to convert the object to a string (or whatever).

So, "just" add a TO_JSON method to the Regexp namespace and you can serialize your regular expressions as strings.

#!perl -w use strict; use JSON::XS 'encode_json'; print encode_json({foo=>'bar'}); my $j=JSON::XS->new;$j->convert_blessed(1) print $j->encode({foo=>qr/bar/}); sub Regexp::TO_JSON{qq($_[0])}"

Update:

After discussion of the topic with choroba, I have to add that it is likely a far better approach to explicitly convert your regular expressions to strings manually. As you are generating the data structure, you should also know at which locations there are regular expressions. Convert these to strings.

Also, I want to question the choice of JSON as a serialization format. If you want speed, there are better approaches that allow serializing regular expressions, like Sereal. If you want something human-editable, YAML at least allows comments, which JSON doesn't allow.