Prashant Tiwari
Prashant Tiwari

Reputation: 117

Print arrays in Perl

I am using Perl in Ubuntu. I have assigned few values to an array and when I am printing the array it is giving some HASH values.

Can anybody assist me with this?

Here is the code.

#!/usr/bin/perl
my $VAR="you are welcome";
my @arr={'1','2','3','4'};
print @arr;
print $VAR."\n";
print "$$ \n";

Here is the output

HASH(0x140cd80)you are welcome 
12548

Upvotes: 1

Views: 283

Answers (2)

009
009

Reputation: 83

Here are some other ways you can use formatting when printing an array in Perl:

print join(", ", @arr);

or

$" = ", ";
print "@arr\n";

Upvotes: 1

Borodin
Borodin

Reputation: 126772

{ ... } generates an anonymous hash, and you have assigned the hash { 1 => '2', 3 => '4' } to the first and only element of @arr.

To set @arr to have four elements containg one through four, you must write

my @arr = ( 1, 2, 3, 4 );

or

my @arr = 1 .. 4;

and then print @arr will output 1234.

If you want to put spaces between the array elements you can just put the array inside double quotes. print "@arr" will output 1 2 3 4

Upvotes: 9

Related Questions