A piece of historical Perl code I have has the following function:
sub binds { join(",", ("?")x$_[0]) }
It is later called with binds(4)
or the like. From what I can tell it is joining ?
s and ,
s but I'm lost as to exactly how, nor do I understand the x$_[0]
part.
This function takes an integer (let's say n
) as its first argument and returns a string of n
question marks separated by commas. Here's how it breaks down:
sub binds {
join(",", ("?") x $_[0]);
# │ │ └──── the first argument to the subroutine.
# │ └── the repetition operator (think multiply).
# └─── a list containing only the string literal "?".
}
binds(4) # => "?,?,?,?"
It's probably a utility function for a database interface to create the specified number of ?
place holders which will be later bound to some specific values as part of an SQL statement.
Let's ask Perl's opinion on how to parse that.
$ perl -MO=Deparse -e'sub binds { join(",", ("?")x$_[0]) }'
sub binds {
join ',', ('?') x $_[0];
}
-e syntax OK
With some whitespace added, the parts become clear.
x
is the repetition operator.$_[0]
is the first subroutine argument, see @_
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With