在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
当前回答
特点:Bash, Korn shell (ksh93)和Z shell都允许使用带或不带美元符号的变量下标数组:
array[index]=$value
array[$index]=$value
加上美元符号,会得到10000的期望值:
unset array
for i in {1..10000}
do
((array[$RANDOM%6+1]++))
done
unset total
for count in ${array[@]}
do
((total += count))
done
echo $total
陌陌性:如果你从RANDOM中移除美元符号,总数将随机变化,甚至大于10000。
类似地,这将产生3而不是2:
a=1; ((r[a++]++)); echo $a
你不能在这里用美元符号,因为这是赋值运算(a在lhs上)虽然你可以用间接的方法,但是双重求值还是会发生。
原因:对于美元符号,变量展开在算术求值之前执行,因此只执行一次。如果没有美元符号,它将执行两次,一次是计算查找的索引,另一次是计算赋值的索引(因此,实际上,循环中第一步的赋值可能看起来像array[4] = $array[6] + 1,这完全打乱了数组)。
其他回答
C + + 1 xλ的:
[] (int x) { std::cout << x << std::endl; } ();
它们可能被滥用在一些奇怪的语法中:
[](){}();[]{[]{}();}();
这是完全有效的c++ 1x。
c#的默认继承模型赢得了我的投票:
public class Animal
{
public string Speak() { return "unknown sound" ; }
}
public class Dog : Animal
{
public string Speak() { return "Woof!" ; }
}
class Program
{
static void Main( string[] args )
{
Dog aDog = new Dog() ;
Animal anAnimal = (Animal) aDog ;
Console.WriteLine( "Dog sez '{0}'" , aDog.Speak() ) ;
Console.WriteLine( "Animal sez '{0}'" , anAnimal.Speak() ) ;
return ;
}
}
运行程序得到如下结果:
狗叫“汪!” 动物说“未知的声音”
获得这种行为应该要求程序员走出程序员的道路。子类实例不会因为被上转换为它的超类型而停止存在。相反,你必须显式地请求预期的(几乎总是想要的)结果:
public class Animal
{
public virtual string Speak() { return "unknown sound" ; }
}
public class Dog : Animal
{
public override string Speak() { return "Woof!" ; }
}
不知道这是不是一个功能。对一些人来说,是的,但对另一些人来说,这可能是一种令人讨厌的行为。不管怎样,我认为这是值得一提的。
在Python中,内置函数round()在Python 2x和Python 3x之间的行为略有不同。
对于Py 2x,
>>> round(0.4)
0.0
>>> round(0.5)
1.0
>>> round(0.51)
1.0
>>> round(1.5)
2.0
对于Py 3x,
>>> round(0.4)
0
>>> round(0.5)
0
>>> round(0.51)
1
>>> round(1.5)
2
我只是不熟悉Py 3x中的round()与0的工作方式。
Py 2x和Py 3x中round()的文档。
下面的答案与这个关于数组的答案类似。
在Powershell中,像其他动态语言一样,字符串和数字在某种程度上是可以互换的。然而,Powershell无法下定决心。
PS> $a = "4" # string
PS> $a * 3 # Python can do this, too
444
PS> 3 * $a # Python doesn't do it this way, string repetition is commutative
12
PS> $a + 3 # Python gives a mismatched types error
43
PS> 3 + $a # Python would give an error here, too
7
如果变量是整数而不是字符串,则操作是可交换的。
PS> $a = 4 # integer
PS> $a * 3
12
PS> 3 * $a
12
PS> $a + 3
7
PS> 3 + $a
7
当有疑问时,做一个模型:
PS> $a = "4"
PS> $b = 3
PS> [int] $a * [int] $b
12
你也可以使用[float]。
在Perl中,可以通过修改一个类的@ISA数组来改变它的继承链,这让我很惊讶。
package Employee;
our @ISA = qw(Person);
# somwhere far far away in a package long ago
@Employee::ISA = qw(Shape);
# Now all Employee objects no longer inherit from 'Person' but from 'Shape'