Skip to content

Instantly share code, notes, and snippets.

@skids
Last active January 16, 2019 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skids/7cc60e21ddcb3dfad1e119af236cc1d2 to your computer and use it in GitHub Desktop.
Save skids/7cc60e21ddcb3dfad1e119af236cc1d2 to your computer and use it in GitHub Desktop.
Neat Perl6 DRY idiom for unpacking named data into locally scoped variables of same name.
# Neat Perl6 DRY idiom
#
# suppose you want to work with named values in a string
# or data structure, and you want to keep the variable
# names the same as the field/key names.
# sample data using a hash just to kep things simple
my %data = :fee(42), :fie<FIE>, :foo<FOO>, :fum(True);
# DRY idiom:
for my ($fee, $fie, $foo, $fum) {
my $fieldname = $_.VAR.name.substr(1,*);
$_ = %data{$fieldname}; # Or whatever to unpack them from a string
}
say "The fee for this is $fee dollars";
@b2gills
Copy link

b2gills commented Jan 16, 2019

For something even DRYer, add it as a function or an operator.

sub infix:<fields-from> ( \vars, %data ) {
  for vars {
    my $field-name = $_.VAR.name.subst(/^\W+/,'');
    $_ = %data{$field-name}
  }
  vars # return vars so that it can be used as part of an expression
}


my %data = :fee(42), :fie<FIE>, :foo<FOO>, :fum(True);

my ($fee, $fie, $foo, $fum) fields-from %data;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment