Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does this subroutine do?

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.

like image 289
WildBill Avatar asked Dec 09 '22 01:12

WildBill


2 Answers

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.

like image 94
maerics Avatar answered Jan 28 '23 22:01

maerics


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 @_.
like image 35
daxim Avatar answered Jan 28 '23 23:01

daxim