The special variable $" is used to separate arrays interpolated in double quotes. By default, it contains a space, but we need the numbers to be adjacent, so we set it locally (i.e. in a dynamic scope) to an empty string.
Another possible short solution is
sub phone_num{"(012) 345-6789"=~s/(\d)/$_[$1]/gr}
The substitution replaces each digit in the template string with the corresponding element of the @_ array which keeps the list of the subroutine arguments. /g means "global", it's needed to replace all the digits, not just the first one. The /r means "return" - normally, a substitution changes the bound left-hand side value, but with /r, it just returns the value.
The special variable
$"
is used to separate arrays interpolated in double quotes. By default, it contains a space, but we need the numbers to be adjacent, so we set it locally (i.e. in a dynamic scope) to an empty string.Another possible short solution is
The substitution replaces each digit in the template string with the corresponding element of the
@_
array which keeps the list of the subroutine arguments./g
means "global", it's needed to replace all the digits, not just the first one. The/r
means "return" - normally, a substitution changes the bound left-hand side value, but with/r
, it just returns the value.Nice, basically what I got.
sprintf
works as well.The regex solution was pretty interesting. Thanks for the explanation!