函数,脚本

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值