What exactly does this subroutine do?

The part of the historical Perl code that I have has the following function:

sub binds { join(",", ("?")x$_[0]) } 

It is later called using binds(4) or the like. From what I can say, he joins ? and , but I lost exactly, as I do not understand the part x$_[0] .

+4
source share
3 answers

This function takes an integer (say, n ) as its first argument and returns a string of n question marks separated by commas. Here's how it breaks:

 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) # => "?,?,?,?" 

This is probably a utility function for the database interface to create a specified number of owners ? which will later be bound to some specific values ​​as part of the SQL statement.

+10
source

Let me ask Perl's opinion on how to parse this.

 $ perl -MO=Deparse -e'sub binds { join(",", ("?")x$_[0]) }' sub binds { join ',', ('?') x $_[0]; } -e syntax OK 

With the addition of some spaces, the details become clear.

  • x is a repetition operator.
  • $_[0] is the first argument to the subroutine, see @_ .
+3
source

This code generates a comma-separated list of question marks that can generate parameter anchor points in a DBI application.

$ _ [0] is the number of bundles, bindings (4) return "?,?,?,?".

+1
source

Source: https://habr.com/ru/post/1401229/


All Articles