Skip to content

Instantly share code, notes, and snippets.

@belden
Last active August 29, 2015 14:03
Show Gist options
  • Save belden/6adb2554ecc027349137 to your computer and use it in GitHub Desktop.
Save belden/6adb2554ecc027349137 to your computer and use it in GitHub Desktop.

Let's say you're writing this a lot:

my %hew_hash;
@new_hash{@keys} = @old_hash{@keys};

In perl 5.20, you'll be able to do that slice as a single assignment:

my %new_hash = %old_hash{@keys};

But in lower perls, you can't write that. So maybe you're just stuck with the two-step assign-and-slice. After all, it's easy enough to write it, and why bother with a function if you don't need it, right?

...maybe. But when you do upgrade to 5.20, you may want to track down all the places where you're doing pre-5.20 slicing, and start using 5.20 slicing. When I know I'm going to want to do a refactoring in the future, I try to make it easy to do that refactoring.

Imagine if you started writing this today:

my %new_hash = hash_slice(%old_hash, @keys);

Then, when perl 5.20 comes out, you can either look for and replace all instances of hash_slice with proper slicing; or you can just change the implementation of hash_slice to use 5.20 slicing.

Your pre-5.20 implementation might look like this:

sub hash_slice(+@) {
  my $hash = shift;
  return map { $_ => $hash->{$_} } @_;
}

And then your 5.20 implementation, if you chose to keep it, would just change to this:

sub hash_slice(+@) {
  my $hash = shift;
  return %{$hash}{@_};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment