- 论坛徽章:
- 0
|
原帖由 兰花仙子 于 2006-3-12 21:14 发表
[quote]原帖由 qaszxc 于 2006-3-12 20:18 发表
1。怎样判断一个字符串是否为空?
unless ($string){ do something; }
Hallo,
The first question seems too simple but really not simple to answer!
It's depend on which context of the given string.
For examples:
my $string; # undefined variable, but with my() localized.
my $string = ""; # defined variable but it's empty string.
my $string = " "; # defined variable but it contains space(s) or tabs.
my $string = 0; # strange??? is boolean false? or exactly integer 0? perl treated it as undef.
my $string = "0"; # defined string with character 0 (zero). perl returns it as undef.
undef $string; # really explicitly as undefined string.
if you don't pay attenction to the context of the given string, you will get an unexpected
result.
For better undstanding to try this:
perl -Mstrict -MData::Dumper -le 'my $s=""; print Dumper($s) unless $s'
perl -Mstrict -MData::Dumper -le 'my $s=""; print Dumper($s) unless defined $s'
perl -Mstrict -MData::Dumper -le 'my $s; print Dumper($s)'
perl -Mstrict -MData::Dumper -le 'my $s="0"; if ($s){print Dumper($s)}'
perl -Mstrict -MData::Dumper -le 'my $s="0"; if ($s ne ""){print Dumper($s)}'
perl -Mstrict -le 'my $s=0; if (defined $s){print "string: >$s<"}'
... more ...
....testing by yourself.
Best, ulmer
---------------------------
Just 4 Fun. |
|