1.无参function:缺省数组参数为$args,输出时各个参数默认以空格为间隔;可以定义$OFS来指定间隔符号;
PS (3) > function hello { "Hello there $args, how are you?" }
PS (4) > hello Bob
Hello there Bob, how are you?
PS (5) > hello Bob Alice Ted Carol
Hello there Bob Alice Ted Carol, how are you?
‘为分隔符
PS (6) > function hello
>> {
>> $ofs=","
>> "Hello there $args and how are you?"
>> }
>>
PS (7) > hello Bob Carol Ted Alice
Hello there Bob,Carol,Ted,Alice and how are you?
既然args输入参数为数组,则可以利用数组的特性输出某些内容,比如:输入参数的个数等等。
PS (1) > function count-args {
>> "`$args.count=" + $args.count
>> "`$args[0].count=" + $args[0].count
>> }
>>
PS H:\>
function add {$args[0] + $args[1]}
add 1 2
3
2.有参函数 function <name> (<$p1 = <expr1> , $p2 = <expr2>>) { <statement list>}
Arguments to commands are separated by spaces
PS H:\>
function substract ($from, $end) {$from - $end}
substract 2 1
1
substract -from 2 -end 1
1
1)常犯的错误是调用函数时:subtract(1,2)
2) 如果有多余的参数输入, 则多余的参数则被存在$args里面;
Here’s a tip: if you want to make sure that no extra arguments are passed
to your function, check whether the length of the $args.length is zero
in the function body. If it’s not zero then some arguments were passed.
PS H:\>
function a ($x,$y)
{
"X is $x"
"Y is $y"
"args is $args"
}
a 1 2
X is 1
Y is 2
args is
a 1 2 3 4 5
X is 1
Y is 2
args is 3 4 5
参数的缺省值function add ($a=1, $b=2) {$a + $b}
add => 3
返回值可以用return
PS H:\> function fact ($x) {
if ($x -lt 2) {return 1}
$x * (fact ($x-1))
}
$k=fact 3
$k
6