Can I autobox a single variable in perl?

Viewed 77

I'm using autobox as it allows me to do use JSON::Path on arbitrary variable like this:

use autobox::JSON::Path;
use Mojo::Util qw/dumper/;

my $w = { foo => 'bar', baz => [ 1, 2, 3 ] };

print dumper $w->get('$.baz');

where autobox::JSON::Path is here (still early code).

This means however that autoboxing affects all hashrefs and arrayrefs.

Is there a way to do it so that it affects only specific variables? or is it actually the same as doing

my $w = autobox::JSON::Path::Get->new({ foo => 'bar', baz => [ 1, 2, 3 ] })

and that's it?

1 Answers

Here is an example of how you can use autobox in combination with JSON::Path. You can restrict the usage of autobox to a specific scope and hence to specific variables like this:

use strict;
use warnings;
use JSON::Path;
use Mojo::Util qw/dumper/;

sub HASH::get {
    my ($hash, $arg) = @_;
    my $path = JSON::Path->new($arg);
    return $path->get($hash);
}

my $w = { foo => 'bar', baz => [ 1, 2, 3 ] };

{
    use autobox;
    print dumper $w->get('$.baz');
}

Output:

[
  1,
  2,
  3
]
Related