Multiple ways to print an array variable in Perl (examples)

This tutorial explains multiple ways to print an array with examples

  • using print with an array variable
  • using join
  • data:dumper
  • JSON::XS
  • map function
  • Data::Printer

Perl Array Print

  • Easy way to print an array formatted in Perl with examples

An easy way to print a variable in Perl using print statements.

if print contains an array variable, It prints all elements with space separation.

@numbers = (1, 2, 3,4,5,6);
print "@numbers\n";

Output:

1 2 3 4 5 6
  • Use Data::Dumper

    Data::Dumper🔗 prints the array or list in a stringified version.

    • First, Import using use Data::Dumper; into a code
    • Next, print the result of Dumper(\@arrayvariable) Here is an example
use Data::Dumper;

@numbers = (1, 2, 3,4,5,6);
print Dumper(\@numbers);

Output:

$VAR1 = [
1,
2,
3,
4,
5,
6
];
  • using the map function

the map is another way to iterate an array or list. with each iteration, Print the iterated value using the current value variable $_.

@numbers = (1, 2, 3,4,5,6);
map{ print "$\_\n" } @numbers;

It prints each element in a new line. Output:

1
2
3
4
5
6
  • using the join function This approach is used if you want a customization of printing the values

For example, print the array values with a hyphen(-) separation.

The join function takes a delimiter from an array and prints the string with a delimiter character separated in an array of values.

@numbers = ("one", "two", "three");
print join("-", @numbers);

Output

one-two-three
  • use Data::Printer It prints the numbers using the p function in the format of []
use Data::Printer;
@numbers = ("one", "two", "three");
p @numbers;

Output:

[
[0] "one",
[1] "two",
[2] "three",
]
  • use JSON::XS function Sometimes, an array contains objects of multiple properties. To print the array into json format, use encode_json of an array as given below
use JSON::XS;
@numbers = ("one", "two", "three");
print encode_json \@numbers

How to print an array in Perl?

To print an array in Perl, Please follow the below steps

  • declare an array of @variable assigned values
  • use a print statement with an array variable
  • It prints an array of elements with space separated.
  • Or you can use one approach from the above multiple ways.