Skip to content

Instantly share code, notes, and snippets.

@timo
Last active September 17, 2018 19:34
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 timo/44efb53aa136871e87b931d1656c8aa9 to your computer and use it in GitHub Desktop.
Save timo/44efb53aa136871e87b931d1656c8aa9 to your computer and use it in GitHub Desktop.
A little operator that lets you mutate an object in a one-liner without needing to use the mutator's return value!
"foobarbaz".comb.Array.splice(3,1,"X").join.say;
# Output: b
# Issue: splice returns what was cut out, not the result.
# Solution: Keep the array of characters around for later.
my @a = "foobarbaz".comb; @a.splice(3,1,"X"); @a.join.say;
# Output: fooXarbaz
# Don't want to introduce a local variable for this?
# Use this beautiful operator to apply a mutation to
# the variable and return the mutated value, rather than
# the mutator's return value
sub postcircumfix:<⦓ ⦔>($a, &code) { my $b = $a; code($a); $b };
# et voilà!
"foobarbaz".comb.Array⦓*.splice(3,1,"X")⦔.join.say;
# Output: fooXarbaz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment