0

If I use => in an array structure like my $arr = [ a => b ];, is it the same thing as my $arr = [a, b];? (Actually I have an unrelated question here, why initializing array this way doesn't require arr prefixed with @? )

Source: http://www.misc-perl-info.com/perl-operators.html

If this is true, then is there a good reason for perl to have this seemingly obscure feature?

doubleDown
  • 8,048
  • 1
  • 32
  • 48
fy_iceworld
  • 656
  • 2
  • 10
  • 20
  • 1
    http://stackoverflow.com/questions/4093895/how-does-double-arrow-operator-work-in-perl#4093914 – Julian Fondren Jun 29 '13 at 03:33
  • 2
    your unrelated question: you're not initalizing an array, `[ ]` creates a *reference* to an anonymous array. `( )` creates an array – BRPocock Jun 29 '13 at 03:44
  • 1
    @BRPocock () creates a list not an array. There is no way to directly create an array or hash from values. Only lists and references to arrays and hashes. – xaxxon Jun 29 '13 at 05:17

2 Answers2

7

The => operator is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores.

Why?

The => operator is helpful in documenting the correspondence between keys and values in hashes, and other paired elements in lists. (source)

mattexx
  • 6,456
  • 3
  • 36
  • 47
6

a => b is the same as 'a', b. Aside from its autoquoting properties, it's useful to imply a relationship. Compare:

Point->new('x', $x, 'y', $y)

Point->new(x => $x, y => $y)

[ ... ] creates an (anonymous) array and returns a reference to it.

 [ ... ]

is similar to

 do { my @a = ( ... ); \@a }

That's why the result is being assigned to a scalar. If you wanted to create an array, you'd use my @a, not [ ].

ikegami
  • 367,544
  • 15
  • 269
  • 518