http://www.perlmonks.org?node_id=1073020


in reply to Re: Creating flexible method accessor
in thread Creating flexible method accessor

Thanks for the help!
Couple of responses/questions:
1. I actually do use strict & warnings at the top of all of my scripts.
2. I actually had a typo in my copying over my routines. I didn't use 'for my $_ (@_)', rather I used 'for (@_)' and then used '$_' to reference the current iterated array element which I thought was always ok. At least it doesn't give me errors in 5.10.0
. 3. I like your way of not using eval.
4. However, I wanted to be able to pass something more general than just 'data'. For example. I might want to access several layers down as in: $self->{data}->{level2}->{level3}' etc. More generally, I would like to pass an arbitrary 'path' to some sequence of hashes and arrays to get/set to the desired accessor element. (btw I am using this to access elements of a JSON-decoded string which typically can be multiple levels deep)
  • Comment on Re^2: Creating flexible method accessor

Replies are listed 'Best First'.
Re^3: Creating flexible method accessor
by puterboy (Scribe) on Feb 02, 2014 at 02:53 UTC
    Disregard #4. I misread what you wrote. It works fine.
      Actually, to clarify -- your suggestion of using ${path} works fine when applied to my original script which allows the multi-level hierarchies I need.

      However, it is not obvious (to me) how to make this work in your non-eval script. If I use ${path}, I get all sorts of errors.

      Unfortunately, the exercise you leave to the reader is actually the exercise that was the point of my original question :) (though I quite appreciate your provided script).

        ${path} is really just a different way of writing $path:

        my $foo = "xyz"; print $foo."bar"; # prints "xyzbar" print "${foo}bar"; # same

        As for making it more flexible: let's say you've got your "path" in an array @path, one way to walk your data structure is: $self = $self->{$_} for @path;

Re^3: Creating flexible method accessor
by Anonymous Monk on Feb 02, 2014 at 04:14 UTC

    for (@_) { whatever($_) } is fine, for my $whatever (@_) just helps readability in case the body of the loop grows to more than a few lines long. But one should stay away from my $_.

    It wouldn't hurt to upgrade your Perl if you can, 5.10.1 was released over 4 years ago. If you're on a multi-user system perhaps your sysadmin has already installed a newer version of Perl in a non-default location, such as under /opt/.

    I see this quite often on PerlMonks and I really don't understand why I see so many "typos when copying"... Ctrl+C, Ctrl+V ???