0

from perlootut:

  my $cage = File::MP3->new(
      path          => 'mp3s/My-Body-Is-a-Cage.mp3',
      content       => $mp3_data,
      last_mod_time => 1304974868,
      title         => 'My Body Is a Cage',
  );

I don't understand what is going on here. It looks auto vivification, if so then new is being passed both the class name and a reference to the new hash?

jason dancks
  • 1,152
  • 3
  • 9
  • 29
  • 1
    Method `new` gets classname and other *list* parameters flattened into `@_` array. There is no hash nor hashref in above code. – mpapec Jan 13 '15 at 06:29
  • then whats going on exactly with `=>` If I wrote a module and wanted to pass parameters with this syntax how would I access it? – jason dancks Jan 13 '15 at 06:31
  • 1
    `=>` in perl is fancy comma; http://stackoverflow.com/a/4093914/223226 `sub new { my $class = shift; my %arg = @_; return bless \%arg, $class; }` – mpapec Jan 13 '15 at 06:33

2 Answers2

5

No autovivification involved. You may be confused by the use of the => operator:

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.

Although => is often used when declaring hashes, it doesn't create a hash by itself.

The code you posted is equivalent to

my $cage = File::MP3->new(
    'path',          'mp3s/My-Body-Is-a-Cage.mp3',
    'content',       $mp3_data,
    'last_mod_time', 1304974868,
    'title',         'My Body Is a Cage',
);

This simply passes a list of eight items to the new method.

Borodin
  • 126,100
  • 9
  • 70
  • 144
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
1

=> is also known as a fat comma, and it acts just like a comma--except when:

  1. the thing on the left is a bareword, and
  2. the bareword would qualify as a variable name(i.e. no strange characters)

In that case, the fat comma will quote the bareword on the left.

The fat comma is used because:

  1. Some people find it easier to type the fat comma than typing quote marks around the bareword on the left

  2. The fat comma indicates a relationship between the lhs and the rhs. However, the relationship is only visual--it's up to the function to determine what the relationship should be.

Although => is often used when declaring hashes, it doesn't create a hash by itself.

To wit:

use strict;
use warnings;
use 5.016;
use Data::Dumper;

my %href = (
    'a', 10,
    'b', 20,
    'c', 30,
);

say $href{'a'};

say Dumper(\%href);


--output:--
10
$VAR1 = {
          'c' => 30,
          'a' => 10,
          'b' => 20
        };

perl ain't ruby.

7stud
  • 46,922
  • 14
  • 101
  • 127