oakb has asked for the wisdom of the Perl Monks concerning the following question:

my ( $yr, $mo, $dm, $dy, $wk )  =  ( $dt->[0], $dt->[1], $dt->[2], $dt->[7], $dt->[8] );

Is there a shorter, simpler, more elegant way to handle the right side of this? I just need selected elements of the referenced array, but normal slicing doesn't work:

( $dt->[0,1,2,7,8] ); # dis no worky!

Yes, I have a working solution. But I hate the clunky longhand that's involved, and I hope the wisdom of the Perl Monks can lead me to enlightenment.

Replies are listed 'Best First'.
Re: Slices from array reference
by davido (Cardinal) on Mar 25, 2014 at 04:47 UTC

    my( $yr, $mo, $dm, $dy, $wk ) = @{$dt}[0,1,2,7,9];

    Dave

      Thank you, Dave, that did the trick. I could swear that I'd tried all different permutations of @{$dt} dereferencing, but I obviously hadn't. I appreciate your extremely quick solution.

        If you hate "magic numbers" appearing scattered throughout a script, you can use enum to set up constants with similar syntax to C:

        # At the top of the script... use enum qw( YR=0 MO DM DY=7 WK ); # ...later... my( $yr, $mo, $dm, $dy, $wk ) = @{$values}[ YR, MO, DM, DY, WK ];

        The same effect can be achieved with the constant pragma, though the setup is a little less convenient.

        Update: I haven't used enum before, but I like how it seems so familiar to someone who has spent time with C or C++. I discovered it when I went looking for a module that would provide the inlinable functions that constant does, but with a declaration syntax closer to the convenience of C's enums. Imagine that; a Perl programmer going looking for C-like convenience!!! That will never happen again. Anyway, why I'm really happy for having found it is because the module's documentation led me to this: Neil Bowers' blog on "CPAN modules for defining constants".


        Dave

        Update: Hmf! I guess after 4300+ posts I'm entitled to an accidental duplicate. But I do apologize for the inconvenience.

        If you hate "magic numbers" appearing scattered throughout a script, you can use enum to set up constants with similar syntax to C:

        # At the top of the script... use enum qw( YR=0 MO DM DY=7 WK ); # ...later... my( $yr, $mo, $dm, $dy, $wk ) = @{$values}[ YR, MO, DM, DY, WK ];

        The same effect can be achieved with the constant pragma, though the setup is a little less convenient.


        Dave

Re: Slices from array reference
by shmem (Chancellor) on Mar 25, 2014 at 18:41 UTC