Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is the difference between $foo = [1,2,3] and @foo = (1,2,3) in Perl?

user-image
Question added by Farah Maher , software developer , IT House Solutions
Date Posted: 2013/07/04
Jörg Löhken
by Jörg Löhken , Software Developer / Architect , Freelance

Ummm, both answers are actually either partly, or completely incorrect.

$foo = [1,2,3] makes $foo a reference to an array with the contents1,2,3, which can be convenient to pass it as a single scalar parameter into a subroutine (as opposed to passing an entire array, where you block all elements of @_ after the array for the subroutine), or define methods on this reference, as soon as you have blessed it into a class. Usually, an object is defined as an empty hash reference {} where you can attach properties and methods to, but [] also works just fine with regards to methods (since properties are simply hash elements of an anonymous hash / hash reference, [] can't have any, since it is not an anonymous hash). Even \\$foo will do for a string.

and @foo = (1,2,3) would define @foo as an array. To treat $foo as an array, you would have to dereference it like this: @{$foo}.

And to make matters more complicated, $foo = (1,2,3) also works, but that would only store the size of the array (1,2,3) in $foo, aka3.

 

Guys, please, if you are not sure of the answers you are giving, do your research and please try out a few lines of code first. You are not helping anybody with answers off the top of your heads.

to define $foo as the third element of [1,2,3] you would need to use $foo = [1,2,3]->[2] which, btw, also shows the different way of addressing array elements. If you have an array, aka @foo, you can address its elements like so: $foo[2]. If you use an array reference (aka $foo = [1,2,3], you treat the same element thus: $foo->[2]

 

To go a bit more in-depth about Perl references, check out this link: http://perldoc.perl.org/perlref.html

Preetham D
by Preetham D , Software Engineer / Senior Software Engineer , Mindtree

@ followed by name indicates as array whereas previous one with $ is variable

$foo is scalar representation in perl, where as @foo is array representation in perl scripting.

$foo has the last element in the list, from above question $foo has the number3.

@foo contains all the elements in the list. From above question @foo has the numbers1,2,3.

I hope i cleared your doubt.

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.