Skip to content

Instantly share code, notes, and snippets.

@hkoba
Created July 2, 2019 03:16
Show Gist options
  • Save hkoba/a2a066543cebcdb2bb678a9c8506859b to your computer and use it in GitHub Desktop.
Save hkoba/a2a066543cebcdb2bb678a9c8506859b to your computer and use it in GitHub Desktop.
JSON::XS refuses to encode a restricted hash to json (while Cpanel::JSON::XS is not).
#!/usr/bin/env perl
use strict;
use warnings;
{
my ($use_cpanel) = @ARGV;
my $class = do {
if ($use_cpanel) {
require Cpanel::JSON::XS;
'Cpanel::JSON::XS'
} else {
require JSON::XS;
'JSON::XS';
}
};
my $m = Mail->new(from => 'foo', to => 'bar', subject => 'xxx', message => 'yyy');
print $class->new->convert_blessed->encode($m), "\n";
}
#========================================
package Mail {
use fields qw/from to subject message/;
sub new {
my $pack = shift;
my $self = fields::new($pack);
%$self = @_;
$self;
}
sub TO_JSON {
my $self = shift;
+{%$self};
}
};
Z-chtholly(pts/0)% ./restricted_hash_json.pl
Modification of a read-only value attempted at ./restricted_hash_json.pl line 21.
Z-chtholly(pts/0)% ./restricted_hash_json.pl 1
{"subject":"xxx","from":"foo","message":"yyy","to":"bar"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment