· 8 years ago · Apr 04, 2018, 06:08 PM
1# Perl References
2
3Simple Perl variables are called `scalars`. Examples of scalar values are
4
5```perl
6 $number = 123;
7 $string = "String";
8 $file_handle = open "<filename";
9 $null_value = undef;
10 $reference = \"Reference of a String";
11```
12
13Perl has a few simple data types. Each is determined from the variable prefix symbol when declared, or when you want a non-scalar set of variables returned.
14
15* $variable - A scalar type
16* @variable - An array type
17* %variable - A hash type
18* & - A code type, though this is never a type of a variable
19
20Complex variables can hold multiple scalar variables. These are Arrays, Hashes, Globs, and Objects.
21
22When references or defining the whole structure, we use the type prefix as above, but when access a scalar value within one, we use the $ prefix to denote
23
24#### Scalar References
25
26A `reference` value does not hold one of these complex data types, but a "pointer" to one. A reference to a scalar can be used with the \\ referencing operator, the [ ] array reference construct, or a { } hash construct.
27
28The reference is dereferenced with the double-dollar ($$refname) variable.
29
30```perl
31 $i = 123; ## A scalar
32 $iref = \$i; #=> SCALAR(0x80108d678) ## Reference to scalar
33 $sref = \"Hello" ## A reference to a string or other literal
34 $$iref; #=> 123; ## Dereferencing the scalar reference
35```
36
37### Array
38
39The array holds a list of scalar values.
40
41```perl
42 @array = (1, 2, 'three', $file_handle, undef);
43 $array[1] #=> 2 ## Second element array (start counting at 0)
44 @array[1,2] #=> (2, 'three') ## A "slice" as list of elements selected from array
45
46 $#array #=> 4 ## Last element index (0..n) of array, -1 if empty.
47 scalar(@array) #=> 5 ## Number of elements in the array, 0 if empty.
48
49 push @array, 123; ## Appends value(s) to the end of the array
50 pop @array; #=> 123 ## Removes and returns the last element of the array
51 unshift @array, 123; ## Prepends value(s) onto the head of the array
52 shift @array #=> 123 ## Removes and returns the first element from the array
53
54 foreach $element (@array) { # The foreach structure iterates over the loop
55 print $element
56 }
57
58 for ($i=0; $i<scalar(@array); $i++) { # The famous C-style for loop can be used
59 print $array[$i];
60 }
61
62 foreach my $i (0..$#array) { # Use the Range operator to iterate over the indexes of the array
63 print "Element $i is $array[$i]\n";
64 }
65
66 # Use map to iterate over the array, returning new array ($_ is the temp variable in block)
67 @array = map { $_ * 2 } @array; # This example doubles the values of each array element
68
69 # Use grep to generate list of elements matching your conditional expression ($_ is temp var)
70 @array = grep { $_ % 2 } @array; # Returns the odd numbers from an array of numbers
71
72```
73#### Array References
74
75To get an array reference, use the [1, 2, 3] syntax to create an array reference, or prefix your array variable with a backslash like \@array.
76
77Dereference an array with @$arrayref, with the $arrayref->[element] arrow for element references, or the @{array_ref_expression} syntax.
78
79```perl
80 @arr = (1,2,3)
81 $aref = \@arr; #=> ARRAY(0x80108d678)
82 @$aref = (1,2,3); #=> ARRAY(0x80108d678) # Alternate syntax for dereferenced assignment
83 @$ref; #=> (1, 2, 3)
84 $aref = [1,2,3] #=> ARRAY(0x80108d678)
85 @$ref; #=> (1, 2, 3)
86 $ref->[1]; #=> 2 ## Second element of array
87 $$ref[1]; #=> 2 ## Alternate syntax
88 $aref = [split(/ /, $sentence)]; # wrap a function to return an array reference instead
89 $aref = [ map { $_ * 2 } @$aref ]; # Using map with an array reference
90 @$aref << $value; #=> Does NOT work (doesn't save array back to reference)
91 push(@$aref, $value); #=> Works!
92
93 scalar(@$aref) #=> 3 ## Number of elements in the referenced array
94  $#$aref        #=> 2 ## Last element index, -1 if empty
95 Â $#{ $aref } Â Â Â Â Â #=> 2 Â ## Last element index, alternate syntax
96 $#{ [] } #=> -1 ## ... Empty arrays return -1.
97
98 foreach my $element (@{ arrayhref_function() }) { ... };
99
100 foreach my $i (0..$#{$aref}) { # Use the Range operator to iterate over the indexes of the array
101 print "Element $i is $aref->[$i]\n";
102 }
103
104 # Arrays can contain other arrays. A "table" is a 2-dimensional array.
105 $table = [ [1,2,3], [4,5,6], [7,8,9] ];
106 $table->[1] #=> [4,5,6]
107 $table->[0][1] #=> 2
108 push( @$table, [10,11,12] ); # Appends new row onto table
109 push( $table->[ $#{$table} ], 13 ); # Appends to last row of the table, $table->[3][3] == 13
110```
111
112### Hash
113
114A Hash is also known as a dictionary or associative array. It provides a key/value structure to set and retrieve values by a key value. It is a special case of a list, and decomposes back into a list when assigned or sent as a function parameter.
115
116```perl
117 %hash = (one=>1, two=>2, three=>3);
118
119 $hash{one}; #=> 1 ## The associated value for the key value of "one"
120 @hash{'one', 'two'}; #=> (1, 2) ## Returns a sliced list of values
121
122 %hash #=> ('one', 1, 'two', 2, 'three', 3) ## Decomposes into a list
123 keys %hash #=> ('one', 'two', 'three') ## List of keys
124 values %hash #=> (1, 2, 3) ## List of values
125 exists $hash{$key} #=> Boolean ## Hash operator returns true if key exists in the hash
126 delete $hash{three}; #=> 3 # Deletes key/value from hash, returns the value
127
128 %hash = %{ hashref_function() };
129
130 while ( ($key, $value) = each %hash) { # Iterates over a hash
131 print $key, $value;
132 }
133
134 foreach $key (keys %hash) { # Iterates over a hash by key value
135 print $key, $hash{$key};
136 }
137```
138
139Note: When iterating over a hash using `each`, it keeps a "cursor" in the hash of the current key/value pair. If you do not finish iterating, the next time you start iterating, it will continue where it left off instead of at the first key/value pair of the hash. To reset the cursor, call `keys %hash` before iteration.
140
141#### Hash References
142
143To get a hash reference, use the {key=>value} syntax instead, or prefix your variable name with a backslash like: \%hash.
144
145Dereference a hash with %$hashref, with the $arrayref->{key} arrow for value references, or the %{array_ref_expression} syntax.
146
147```perl
148 %hash = (one=>1, two=>2, three=>3);
149 $href = \%hash; #=> ARRAY(0x80108d6f0) ## Hashes are also arrays
150 %hash = %$href; #=> ('one', 1, 'two', 2, 'three', 3)
151 $href = {one=>1, two=>2, three=>3};
152 #=> ARRAY(0x80108d6f0) ## Hashes are also arrays
153 $href->{one}; #=> 1 # Access a value by reference
154 $$href{one}; #=> 1 # Alternate syntax
155
156 keys %$href #=> ('one', 'two', 'three') ## List of keys
157 values %$href #=> (1, 2, 3) ## List of values
158 exists $href->{$key} #=> Boolean ## Hash operator returns true if key exists in the hash
159 delete $href->{three}; #=> 3 # Deletes key/value from hash, returns the value
160
161 foreach $key (keys %$href) { print $key, $href->{$key}; } # Iterate over Hash Reference
162 while ( ($key, $value) = each %$href) { print $key, $value; }
163
164 # Hashes can contain other hashes!
165 $href = {one=>1, word_counts=>{"the"=>34, "train"=>4} };
166 $href->{word_counts}{the} #=> 34
167 @words = keys( %{ $href->{word_counts} } ); # De-reference inner hash with %{...} construct
168```
169
170## Usage: Passing data to functions
171
172When you call a Perl function, it generates an array of the arguments and invokes the function. The function uses the special default array variable, @_ and uses the positions of the arguments as the parameters.
173
174```perl
175 myfunction($i, $s); #=> sets @_ = (123, "String");
176```
177
178The called function parses the incoming argument list with standard Perl notation:
179
180```perl
181 ($first, $second, @rest) = @_;
182```
183
184That statement takes the incoming argument array, and puts the first element in $first, the second in $second, and the remaining arguments (if any) to into the @rest array.
185
186When you pass an array or hash (which is really just an array anyway) to a function, it "flattens" out the array and passes each value of the array as a positional parameter.
187
188```perl
189 myfunction($i, @arr, %hash); #=> sets @_ = (123, 1, 2, 3, 'name', 1, 1, "one", "etc.", $i);
190```
191
192Oops! Now myfunction() doesn't know where the array begin and ends, nor where the hash begins or ends. The only thing it knows for sure is the first argument since that in a simple scalar.
193
194This can be desired, as long as each parameter is a simple value, and the last parameter is an array or hash.
195
196```perl
197 myfunction($i, @arr); #=> Sets @_ to (123, 1, 2, 3);
198 #...
199 sub myfunction {
200 my ($i, @arr) = @_; #=> allows function to reconstruct the parameters
201 }
202```
203
204But what if you need to pass both an array AND a hash to a function? This is where references save the day. Since a reference to an array or hash is a single value, the reference to the whole array takes only one positional argument.
205
206
207```perl
208 myfunction($i, \@arr, \%hash);
209 #...
210 sub myfunction {
211 my ($i, $aref, $href) = @_; #=> $i is 123, $aref and $href are references.
212 @$aref; #=> (1, 2, 3)
213 %$hash; #=> (name=>1, 1=>"one", "etc."=>$i)
214 }
215```
216
217Function can also use this technique to return an array of values to a caller.
218
219```perl
220 return ($i, \@arr, \%hash);
221```
222
223There is also an added performance benefit of passing references instead of whole arrays and hashes. For large structures, it takes time copying each element from the array into the @_ variable. Instead, only a single reference variable is needed to be passed into the @_ argument list. In computer science, this is known as "passing by reference" instead of "passing by value".
224
225Lastly, when you pass a reference into a function, that function can change the value of the passed variable "in place" without getting returned explicitly. This technique is useful at time, but sometimes these "side effect" practices are discouraged, so use this only when it makes sense, okay?
226
227```perl
228 sub myfunction {
229 $iref = shift; # Shifts first value off of @_ array
230 ++$$iref; # Increment the value at the reference
231 }
232 #...
233 $j = 123; #=> 123
234 myfunction(\$j); # myfunction() will change the value of $j
235 $j; #=> 124
236```
237
238While this example demonstrated the concept, this is one of those cases where it is not okay to do this. I would instead not use the reference and have the code return the new value.
239
240### Simulating The Ruby Call
241
242NOTE: This is more advanced and references techniques from later in this document. If you are new to this topic, feel free to skip onto the next section.
243
244In the Ruby (1.9) language, which names Perl as a close ancestor, You can call a function like this:
245
246```ruby
247 my_func(data, hashkey:"value", hashkey2:123) { "This is a closure" }
248
249 def my_func(data, options={}, &block)
250 options #=> { hashkey: "value", hash_key2: 123 }
251 block.call #=> "This is a closure"
252 end
253
254 my_func2(1, 2, 3, 4, 5, 6, 7, 8, debug:true) { |x| x * 2 }
255
256 def my_func2(*args)
257 args #=> [1, 2, 3, 4, 5, 6, 7, 8, {debug: true}]
258 options = args.last.is_a?(Hash) ? args.pop : {} #=> {debug: true}
259 args #=> [1, 2, 3, 4, 5, 6, 7, 8]
260 args.map {|x| yield(x) } # The passed block is called with yield
261 end
262```
263
264Notice that the calls that look like named parameters ```hashkey:"value"``` are pooled into a hash and appended to the call arguments, that my_func captures in the variable ```options```. If a block is specified on the call, it will be assigned to a variable at the end starting with the ampersand like ```&block``` (though is still available using the yield command if not captured as such).
265
266In ```my_func2```, we expect any number of arguments, and the unspecified ones are assigned to the variable ```args``` using the "splat" (*) operator. This is how a perl function is invoked, where the parameters are assembled into an array, and the function must parse out the variables at the positions it expects.
267
268However, any name-value pairs specified at the end of the call are put into a hash, which is still passed as the last element of the args array. If we don't expect the args array to end with a hash, we can use this trick to pop off the hash as the last element of the args array, which we can use to control preferences for the function.
269
270We can use this trick as well with Perl when we also would not otherwise expect the last argument to be a hash reference or a closure (anonymous function reference).
271
272```perl
273 my_func2(1, 2, 3, 4, 5, 6, 7, 8, {debug=>1}, sub { 2 * shift });
274
275 sub my_func2 {
276 # Check if last argument is a CODE block...
277 my $block = scalar(@_) && ref($_[-1]) eq 'CODE' ? pop : sub {shift}; # Passed Closure?
278
279 # You can either do this to put the optional arguments into a hash reference...
280 my $options = scalar(@_) && ref($_[-1]) eq 'HASH' ? pop : {}; # as Hash Reference
281
282 # ... Or this to dereference it and store in a hash
283 my %options = scalar(@_) && ref($_[-1]) eq 'HASH' ? %{pop()} : (); # as Hash
284
285 my @args = @_; #=> (1, 2, 3, 4, 5, 6, 7, 8)
286 map { &$block($_) } @args;
287 }
288```
289
290Here, I inspected the special @_ argument array to see if the last element ($_[-1], we use $_ to access an element from @_, and the -1 index tells perl to wrap back around to the end of the array to point to the last element) is a code or hash reference. If it was, I use ```pop``` to take it off the end of the array, otherwise I set it to a default (empty) value.
291
292
293
294## Usage: Data Structures
295
296A `table` or 2-dimensional array is not a native perl datatype as it is in many languages. Instead, perl allows you to build your own as an array of arrays. Now since perl array elements can only be scalar variables, we need to use a reference instead. So a perl table is actually an array of references.
297
298```perl
299 @row1 = (1, 2, 3);
300 @row2 = (4, 5, 6);
301 @table = (\@row1, \@row2);
302
303 $table[0]->[1]; # => 2 ## Value of first row, second column
304 $table[0][1]; # => 2 ## Any second-level subscript/hash on array implies the ->
305```
306
307Often, it's best to bite the bullet and fully embrace a reference when you are using a data structure like this. It helps me to think of it as a starting point, and makes the syntax more friendly in the long run.
308
309```perl
310 $table = [ [1,2,3], [4,5,6] ]; # Table is a reference of arrays of arrays :-)
311 $table->[0][1]; #=> 2
312 $table[0][1]; # Wrong! # Error! Expecting $table[0]->[1] but $table is a reference, not array
313```
314
315See how I defined the table using the [ ] array reference syntax? It should make it more clear to write and read. Also, the table subscripts are now together, not separated by the -> dereferencing pointer.
316
317Also, see the difference of addressing table elements set up as starting with an array instead of a array reference? It can trip you up, and I suggest always use a reference to avoid the confusion, because mixing syntax styles in a program is painful. Using a consistent syntax within a large program and complex data structures reduces chances for errors.
318
319```perl
320 @table = ([1,2,3], [4,5,6]); # Avoid: array of references
321 $table[0][1]; #=> 2 ## While this works nicely...
322 $table[0]->[1]; #=> 2 ## ... this is what perl does
323
324 $table = [ [1,2,3], [4,5,6] ]; # Suggested: start off with a reference
325 $table->[0][1]; #=> 2 ## Only way to access the element
326
327 $reference->{key} # This makes a consistent usage for all data structures
328 $reference->{key}[0]; # ... Hash of arrays
329 $reference->[0]{key}; # ... Array of hashes
330```
331
332A result set of database rows are best represented as an array of hash references, where each row is a (colname=>value) hash. Again, let's start with a reference to the result set.
333
334```perl
335 $rows = []; # Initialize $rows as array reference
336 push @$rows, {id=>1, name=>"Allen"}; # Add first row, a hash reference.
337 push @$rows, {id=>2, name=>"Bob"}; # Second row
338
339 # Get at the data by $rows->[row_number]{column_name_as_hash_key}
340 $rows->[0]{name}; #=> Allen
341```
342
343Did you follow all that? You may want to parse through it a few times. Here are a few notes:
344
345* @$rows - Push expects an array, we use the @ to dereference the as an array so push can do its thing.
346* {column_name=>row_column_value} - We use the {} hash reference syntax to create the data row.
347* $rows - This returns an array reference for the result set
348* $rows->[0] - returns the first row on the rows array, which is a hash reference
349* $rows->[0]{name} - returns the corresponding value for the key "name" in the first row.
350
351## Dereferencing References of References
352
353Now for the fun part. We saw how to dereference a reference with the `<typeoperator>$referencevariable` syntax and -> operator to navigate through a series of nested references.
354
355```perl
356 @arr = @$array_reference;
357 %hash = %$hash_reference;
358 $i = $$scalar_reference;
359
360 $array_reference->[0];
361 $hash_reference->{key};
362 $array_of_hashes->[0]{key};
363 $array_of_arrays->[0][2]; ## a 2-Dimensional table
364 $three_dim_table->[0][1][2];
365 $arr_hash_array->[1]{key}[2];
366```
367
368Now say we want to operate on a array reference returned from the -> operator. To dereferences an expression like this we use the `@{expression}` syntax for an array reference and the `%{expression}` syntax for a hash reference.
369
370Here is now this works with our 2-dimensional table structure
371```perl
372 $table = [ [1,2,3], [4,5,6] ];
373 $table->[0]; # Returns a reference to [1,2,3]
374 @row = @{$table->[0]}; # Returns the array of (1, 2, 3)
375 push @{$table->[0]}, 0; # $table is now [ [1,2,3,0], [4,5,6] ]
376
377 scalar(@{$table->[1]}) #=> 3 ## The number of items of the second row
378 $#{$table->[1]} #=> 2 ## Index of last element in the referenced array (-1 when empty)
379 @{$table->[1]}[1, 2] #=> (5, 6) ## Slice of array, returns table[1][1,2] as a list
380
381 foreach $row_ref (@$table) { # Iterate over each row
382 foreach $value (@$row_ref) { # Iterate over each column in that row
383 $value; # Do something with each value in the table
384 }
385 }
386
387 for ($i=$#{$table}; $i>=0; $i--) { # Reverse iteration by index
388 for ($j=$#{$table->[$i]}; $j>=0; $j--) { # ... reverse iteration for each row
389 $table->[$i][$j] += $prev; # Do something with that referenced location
390 $prev = $table->[$i][$j]; # ... Totally contrived example
391 }
392 }
393
394 foreach my $i (0..$#{$table}) { # Again, using the range operator
395 foreach my $j (0..$#{$table->[$i]}) {
396 print "table row $i column $j is: $table->[$i][$j]\n";
397 }
398 }
399```
400
401Now let's look at our result set "Array references of hash references"
402```perl
403 $rows = [ {id=>1, name=>"Allen"}, {id=>2, name=>"Bob"} ]; # Array Ref of Hashes
404 $rows->[0]; # Returns reference to the first row
405 %hash = %{$rows->[0]}; # Deferences the first row as a hash
406 @hash_keys = keys %{$rows->[0]}; # ... and now return its keys
407
408 foreach $hash_key (keys @{$rows->[0]}) { } # Iterate over the keys
409 while (($k,$v) = each %{$rows->[0]) { } # Iterate over the "row"
410
411 foreach $row_ref (@$rows) { # Iterate over each row
412 while (($k,$v) = each %{$rows->[0]) { # Iterate over each key-value pair
413 ($k, $v); # Do something with each pair
414 }
415 }
416```
417
418## Inspecting the reference for type
419
420Okay, now imagine you need to write a subroutine that takes a reference, and need to determine what the datatype is for the reference?
421
422The `ref` unary operator takes a variable and returns the datatype. It is the "type of" operator, but does not distinguish between scalar types (string, number, undef, file handles).
423
424```perl
425 ref 'asdf' #=> '' ## Non-reference values return the empty string
426 ref [1,2,3] #=> 'ARRAY'
427 ref {a=>12} #=> 'HASH'
428 ref sub {} #=> 'CODE' ## Code object (see below)
429 ref \123 #=> 'SCALAR' ## Reference to a scalar
430 ref new MyClass #=> 'MyClass' ## Objects return their package/class name
431
432 ref undef #=> '' ## Even undefined values (null/nil) are scalar
433 defined(undef); #=> False ## A False condition, but no value returned
434
435 $r = [{a=>1}];
436 ref $r #=> 'ARRAY' ## Array of Hashes
437 ref $r->[0] #=> 'HASH' ## Deference to the Hash
438```
439
440Congratulations, you are now a master of basic perl references!
441
442## References to Code
443
444But wait! There's more! You can also have references to "code" functions and closures. Older versions of perl used the `&myfunction()` syntax to call a function, but the & operator has been dropped as it was not necessary. However, it is still needed to deferences a code reference.
445
446```perl
447 sub myfunc { 123; } # A simple function
448
449 $code_ref = \&myfunc; # Take a reference to your subroutine
450
451 # These do not work! &myfunc() will alway run the function, not reference it
452 &myfunc(); #=> 123 ## The parens executes the code
453 \&myfunc(); #=> SCALAR(0x100804ed0) ## Executes Returns ref to 123
454
455 @array = my_map(\@array, \&myfunc); # Pass code reference to another function.
456
457 # Execute the code reference. We can also pass in any arguments it needs.
458 &$code_ref(); #=> 123
459```
460
461### Closures
462
463Closures are a cool trick, stolen outright from the Lisp universe. It is a block of code that is passed to another function or stored for later execution, much like we saw before.
464
465The really cool part is this code block executes in the *context* of when it was defined. It has access to all the variables in the scope when it was created, and can alter them, even when invoked from within another function.
466
467One of the useful things we can do with closures is to create a callback code block that injects our specific logic into a general purpose routine.
468
469Closures are "anonymous code blocks" using the `sub { }` syntax (like a subroutine definition without a name).
470
471```perl
472 $i = 1;
473 $closure = sub { ++$i; } # Reference to a closure
474 &$closure(); # Run the reference
475 $i; #=> 2
476```
477
478Let's build a useful function to tie this all together. Perl has a `map` construct that iterates over an array, injects a value into a block, and returns an array of values returned from the block. It does *not* use a closure, but it a language syntax construct. For instance:
479
480```perl
481 @array = ( 1, 2, 3);
482 @array = map { $_ + 1 } @array; # Adds 1 to each element in the array
483 @array #=> (2, 3, 4)
484
485 # Alternate (non-map) way to do this:
486 @result = ();
487 foreach (@array) { push @result, $_ + 1; }
488 @array = @result;
489```
490
491It's a simple, but rather ugly syntax. It sets the $_ variable inside the block for each value of the array.
492
493Suppose we want to create an map-like iterator for a hash. We can write a general routine, map_hash(), that iterates over a hash, and executes a passed closure (or code block) for each key-value pair. The routine passed back a key-value pair, either the same or changed. map_hash() returns a new hash of the result pairs.
494
495```perl
496 sub map_hash {
497 ($hash_ref, $block_ref) = @_; # Args: map_hash(\%hash, sub {} );
498 keys %$hash_ref; # Resets hash iterator in case it was not finished
499 %result = ();
500 while ( ($k,$v) = each %$hash_ref) {
501 ($k, $v) = &$block_ref($k, $v); # Calls the closure or code block
502 %result{$k} = $v; # Place new key-value in result hash
503 }
504 %result; # Returns the new hash
505 }
506
507 # Call map_hash to upper-case the keys of a hash.
508 %hash = (a=>1, b=>2);
509 %hash = map_hash(\%hash, \&uc_hash_keys);
510 %hash; #=> (A=>1, B=>2)
511
512 sub uc_hash_keys {
513 ($k, $v) = @_; # Input arguments: key, value pair
514 (uc $k, $v); # Return upper-cased key, value pair
515 }
516
517 # Call map_hash to sum the values of all keys in the hash
518 $total = 0; # The closure has access to all local vars!
519 %hash = map_hash(\%hash,
520 sub { # Create a closure to
521 ($k, $v) = @_; # Input arguments: key, value pair
522 $total += $v; # Adds value to total defined above
523 ($k, $v); # Return unchanged key, value pair
524 }
525 );
526 $total; #=> 3
527```
528
529# Classes and Object Oriented Perl
530
531Wait! What is this doing here? We are talking about Perl References, right? Well, the perl object model really is just a reference "blessed" with a package name. You can execute any method (a function in OOP is now called a method) in that package using the -> operator.
532
533```perl
534package Person; # Define our Person class
535
536sub new { # Constructor method
537 ($class, %attributes) = @_; # * Receives the package and any arguments
538 my $self = \%attributes; # * Create a hash reference as instance
539 bless $self, $class; # * Tells perl $self is an instance of Person
540} # * bless returns $self, which is returned to caller
541
542sub talk {
543 ($self, $message) = @_; # Self is the object reference always passed in
544 print "$self->{name} says $message \n";
545}
546
547package main; # Change back to our "main" namespace
548
549$person = {id=>1, name=>"Allen"}; # $person is a hash reference
550bless $person, Person; #=> Person=HASH(0x100804ed0), instance created without "new"
551
552# Or we can use the "new" syntax we see in other languages
553$person = new Person(id=>1, name=>"Allen")
554
555# Now $person is a instance of class Person (implemented with a hash).
556
557# Call a method on the person object reference
558$person->talk("hi"); #=> Allen says hi
559
560# This is syntax-sugar for the true calling notation (which explains the $self arg)
561$person = Person::new(Person, id=>1, name=>"Allen");
562Person::talk($person, "hi");
563```
564
565Of course, there is more to understand about object-oriented perl than this basic example. I wanted to demonstrate that perl objects are also references, and require the same syntax.
566
567Also, you see that all perl objects are specially "blessed" references of perl hashes, arrays, or other things you can reference. Though, you will find that 99.99% of the time, it will be a hash, because the hash keys become the instance variables of the object.