Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Data::Printer handle array slices?

Tags:

perl

Apparently not:

use strict;
use warnings;
use Data::Printer;

my @values = 1 .. 99;
p @values[0..9];

Returns

10

The documentation doesn't shed any light on the matter as far as I can tell.

Questions

  • Why doesn't the code above work?
  • Is it possible to make it work without resorting to a temp?
like image 838
Zaid Avatar asked Sep 28 '16 14:09

Zaid


2 Answers

The prototype on Data::Printer::p is \[@$%&];%, so it will accept a named array but not an arbitrary list or anonymous array reference.

There is a Data::Printer::p_without_prototypes function that will accept this input, and if you import Data::Printer with

use Data::Printer use_prototypes => 0;

then p in the current package will refer to this function, and accept your input.

use Data::Printer use_prototypes => 0;
my @values = 1 .. 99;
p [@values[0..9]];
like image 102
mob Avatar answered Nov 18 '22 13:11

mob


Data::Printer's p expects a single variable, but an array slice isn't a variable.

Option 1 (Poor)

Call p for each element of the slice.

use Data::Printer;
my @values = 100 .. 199;
p $_ for @values[0..9];

Output:

100
101
102
103
104
105
106
107
108
109

I say this is poor because it doesn't show the offsets, and more importantly, it can result in no output at all if the list of indexes is empty.

Option 2 (Better)

Build an array.

use Data::Printer;
my @values = 100 .. 199;
p @{ [ @values[0..9] ] };

This produces clearer output than the first option:

[
    [0] 100,
    [1] 101,
    [2] 102,
    [3] 103,
    [4] 104,
    [5] 105,
    [6] 106,
    [7] 107,
    [8] 108,
    [9] 109
]

If you find that too complicated, you could override p's prototype and pass a reference to the array instead.

use Data::Printer;
my @values = 1 .. 99;
&p( [ @values[0..9] ] );

If you're ok with always passing a scalar or a reference (rather than variables) to p, you can use the following:

use Data::Printer use_prototypes => 0;
my @values = 1 .. 99;
p [ @values[0..9] ];
like image 25
ikegami Avatar answered Nov 18 '22 13:11

ikegami