perl脚本中的$_变量

sh/bash/dash/ksh/zsh等Shell脚本
回复
slimhigh
帖子: 67
注册时间: 2010-05-06 19:29

perl脚本中的$_变量

#1

帖子 slimhigh » 2012-01-02 21:34

刚开始学习perl,对$_变量有些小疑惑。
我有一个文件emp.lst如下

代码: 全选

2233|a.k. shukla      |g.m.     |sales     |12/12/52|6000
9876|jai sharma       |director |production|12/03/50|7000
5678|sumit chakrobarty|d.g.m.   |marketing |19/04/43|6000
2365|barun sengupta   |director |personnel |11/05/47|7800
5423|n.k. gupta       |chairman |admin     |30/08/56|5400
1006|chanchal singhvi |director |sales     |03/09/38|6700
我想提取显示第一列的数据。我用如下代码:

代码: 全选

#!/usr/bin/perl
while(<>){
	split(/\|/);
	print "$_[0]\n";
}
我的想法是,split()函数默认拆分$_变量。然后自动填充数组@_,那么此时$_[0]存的就应该是第一列的数字了。
但是结果输出是空白行。

然后我改了代码如下:

代码: 全选

#!/usr/bin/perl
while(<>){
	@str=split(/\|/);
	print "$str[0]\n";
}
这次我得到了正确的答案。我不知到我第一次的代码为什么会错误。我的参考书上说的是:split()函数如果没有显式的赋给变量,那么默认把拆分后的字段赋值给@_数组。我有什么地方用的不对吗?
头像
ChenFengyuan
帖子: 770
注册时间: 2008-03-23 0:39

Re: perl脚本中的$_变量

#2

帖子 ChenFengyuan » 2012-01-03 8:48

什么参考书?
我看了下手册,没有提到默认会赋值给@_
slimhigh
帖子: 67
注册时间: 2010-05-06 19:29

Re: perl脚本中的$_变量

#3

帖子 slimhigh » 2012-01-03 9:39

ChenFengyuan 写了:什么参考书?
我看了下手册,没有提到默认会赋值给@_
《UNIX原理与应用》(印度) Sumitabha Das著 吴文国译
难道是书上写错了??!
slimhigh
帖子: 67
注册时间: 2010-05-06 19:29

Re: perl脚本中的$_变量

#4

帖子 slimhigh » 2012-01-03 9:40

ChenFengyuan 写了:什么参考书?
我看了下手册,没有提到默认会赋值给@_
能不能把手册链接发给我
头像
Strange
帖子: 1824
注册时间: 2006-05-19 9:54
来自: Shanghai

Re: perl脚本中的$_变量

#5

帖子 Strange » 2012-01-03 11:54

$_
The default input and pattern-searching space.

@_
Within a subroutine the array @_ contains the parameters passed to that subroutine.

http://perldoc.perl.org/perlvar.html
ニンニク入れますか?
x60 with gentoo
头像
ChenFengyuan
帖子: 770
注册时间: 2008-03-23 0:39

Re: perl脚本中的$_变量

#6

帖子 ChenFengyuan » 2012-01-03 14:23

slimhigh 写了:
ChenFengyuan 写了:什么参考书?
我看了下手册,没有提到默认会赋值给@_
能不能把手册链接发给我
perldoc -f split
头像
eexpress
帖子: 58428
注册时间: 2005-08-14 21:55
来自: 长沙

Re: perl脚本中的$_变量

#7

帖子 eexpress » 2012-01-03 17:07

默认会赋值给@_
没听说过。
只有$_就有缺省。

安装perl-doc包。才有Perlodc -f
● 鸣学
头像
ChenFengyuan
帖子: 770
注册时间: 2008-03-23 0:39

Re: perl脚本中的$_变量

#8

帖子 ChenFengyuan » 2012-01-03 20:25

eexpress 写了:默认会赋值给@_
没听说过。
只有$_就有缺省。

安装perl-doc包。才有Perlodc -f
用gentoo的表示,装了dev-lang/perl就有perldoc :em09
tusooa
帖子: 6548
注册时间: 2008-10-31 22:12
系统: 践兔
联系:

Re: perl脚本中的$_变量

#9

帖子 tusooa » 2012-01-28 15:30

代码: 全选

● perl -we 'split /,/, "foo,bar"'
Useless use of split in void context at -e line 1.
明明是void context.咋会@_默认。

代码: 全选

] ls -ld //
tusooa
帖子: 6548
注册时间: 2008-10-31 22:12
系统: 践兔
联系:

Re: perl脚本中的$_变量

#10

帖子 tusooa » 2012-01-28 15:32

碰到这样的问题,多use warnings;

代码: 全选

] ls -ld //
回复