Last active
September 17, 2018 19:34
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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