Multiple ways to print an array in Perl with an example

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

Easy way to print an array with 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
  • Using 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 $_.

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

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 below steps

  • declare an array @variable assigned values
  • use print statement with array variable
  • It prints array of elements with space separated.