in reply to Re: Slices from array reference
in thread Slices from array reference

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.

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

    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

      Since groups of 'magic' constants are sometimes used (e.g., for taking/assigning equivalent slices from/to different arrays), here's my trick for keeping everything together. Grouping may be discussed in Neil Bower's interesting blog post, but I've not read through it all yet to find out.

      c:\@Work\Perl\monks>perl -wMstrict -le "use constant DATE_MAGIC => (0, 1, 2, 7, 5); ;; my $dt = [ localtime ]; my ($sec, $min, $hr, $yday, $yr) = @{ $dt }[ DATE_MAGIC ]; print qq{yr $yr yday $yday hr $hr min $min sec $sec}; " yr 114 yday 83 hr 12 min 22 sec 13
Re^3: Slices from array reference
by davido (Cardinal) on Mar 25, 2014 at 05:14 UTC

    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