Next: , Previous: , Up: Functions for Transforming Text   [Contents][Index]


8.5 The let Function

The let function provides a means to limit the scope of a variable. The assignment of the named variables in a let expression is in effect only within the text provided by the let expression, and this assignment doesn’t impact that named variable in any outer scope.

Additionally, the let function enables list unpacking by assigning all unassigned values to the last named variable.

The syntax of the let function is:

$(let var [var ...],[list],text)

The first two arguments, var and list, are expanded before anything else is done; note that the last argument, text, is not expanded at the same time. Next, each word of the expanded value of list is bound to each of the variable names, var, in turn, with the final variable name being bound to the remainder of the expanded list. In other words, the first word of list is bound to the first variable var, the second word to the second variable var, and so on.

If there are more variable names in var than there are words in list, the remaining var variable names are set to the empty string. If there are fewer vars than words in list then the last var is set to all remaining words in list.

The variables in var are assigned as simply-expanded variables during the execution of let. See The Two Flavors of Variables.

After all variables are thus bound, text is expanded to provide the result of the let function.

For example, this macro reverses the order of the words in the list that it is given as its first argument:

reverse = $(let first rest,$1,\
            $(if $(rest),$(call reverse,$(rest)) )$(first))

all: ; @echo $(call reverse,d c b a)

will print a b c d. When first called, let will expand $1 to d c b a. It will then assign first to d and assign rest to c b a. It will then expand the if-statement, where $(rest) is not empty so we recursively invoke the reverse function with the value of rest which is now c b a. The recursive invocation of let assigns first to c and rest to b a. The recursion continues until let is called with just a single value, a. Here first is a and rest is empty, so we do not recurse but simply expand $(first) to a and return, which adds b, etc.

After the reverse call is complete, the first and rest variables are no longer set. If variables by those names existed beforehand, they are not affected by the expansion of the reverse macro.


Next: The foreach Function, Previous: Functions for Conditionals, Up: Functions for Transforming Text   [Contents][Index]