Skip to content
Perl

Subroutines and References

Define subs and use references for complex data.

By EZ4Code Team
subroutinereference

Code

use strict;
use warnings;

# Basic sub
sub greet {
  my ($name, $greeting) = @_;
  return "$greeting, $name!";
}
print greet("Alice", "Hi");  # "Hi, Alice!"

# Named arguments (via hash)
sub create_user {
  my %args = @_;
  return "User: $args{name}, $args{age}";
}
print create_user(name => "Bob", age => 25);

# Array reference (scalar pointing to array)
my @nums = (1, 2, 3);
my $arr_ref = \@nums;
print $arr_ref->[0];      # 1 (arrow syntax)
print @$arr_ref;          # 123 (dereference)
my $first = $arr_ref->[0];

# Hash reference
my %person = (name => "Alice", age => 30);
my $hash_ref = \%person;
print $hash_ref->{name};  # Alice

# Anonymous arrays/hashes
my $anon_arr = [1, 2, 3];
my $anon_hash = { a => 1, b => 2 };

# Array of hashes (common pattern)
my @people = (
  { name => "Alice", age => 30 },
  { name => "Bob",   age => 25 },
);
for my $p (@people) {
  print "$p->{name}: $p->{age}\n";
}

Explanation

Arguments come in @_. References (scalars starting with \) let you nest data structures (arrays of hashes, etc.). -> dereferences: $arr->[0] or $hash->{key}. Anonymous constructors [] and {} create refs inline. Always pass references to subs for large data (avoids copying). Use my for lexical scope; our for package globals.

More Perl Snippets