basics advanced
How to use postfix dereferencing in Perl
Question
What is postfix dereferencing and how do I use it in modern Perl?
Postfix dereferencing (Perl 5.20+) provides a more readable syntax for dereferencing references:
use v5.20;
use strict;
use warnings;
use feature 'postderef';
no warnings 'experimental::postderef';
my $aref = [1, 2, 3, 4, 5];
my $href = { a => 1, b => 2, c => 3 };
# Old syntax
print "@{$aref}\n"; # 1 2 3 4 5
print "$href->{a}\n"; # 1
# Postfix syntax (more readable)
print "@{$aref->@*}\n"; # Not quite...
print $_->@*, "\n" for $aref; # Actual postfix
# Array dereference
for my $item ($aref->@*) {
print "Item: $item\n";
}
# Hash dereference
for my $key ($href->%*) {
print "Key: $key\n";
}
# Slicing
my @slice = $aref->@[0,2,4];
print "Slice: @slice\n"; # 1 3 5
Postfix dereferencing became stable in Perl 5.24. It's more readable when chaining operations.