Learning Perl,4th Edition(2-4 scalar variables)
来源:互联网 发布:数据分析方法五种 编辑:程序博客网 时间:2024/06/05 10:41
2.4 Scalar variables
一个变量是一个盛一个或多个值的容器的名字。 这个变量的名字在程序中保持不变,但是它的值通常会重复变化在程序执行的过程中。
正如你看到的,一个scalar variable 可以盛放一个值,但是其它类型的变量,如数组和
哈希表,可以盛很多值。
一个scalar variable 正如你所想的盛放一个单独的值,它的名字以一个美元符号开始接perl的标志符号:一个字母或者下划线,或者多个字母,数字,或者下划线。另一个对这个的想法是它从一个字母数字或者下划线开始但是不能从一个数字开始。是区分大小写的:$Fred是一个不同的变量与$fred相比。并且所有的字母,数字和下划线都是有效的:
$a_very_long_variable_that_ends_in_1
这个变量是跟下边的不同的:
$a_very_long_variable_that_ends_in_2
Scalar变量总是以开头的$起始。
你应该选择那些有意义的变量名来指示变量的用处。例如,$r很可能意思不明确但是 $line_length就明确。
一个变量只在两三行内使用可以叫作$n,但是一个变量在整个程序中使用就应该有一个有意义的名字。
如果适当的添加下划线可以使一个名字更容易去读和理解。尤其是你的维护程序员具有不同的口语背景的时候。例如:$super_bowl是一个比$superbowl更好的名字,因为后者可以被看作$superb_owl。一个$stopid是$sto_pid(存贮一个process id?)还是$s_to_pid(转换到pid?)或者$stop_id(停止一个id),或者它本来就是一个stopid被拼错了。
所有的变量名字在perl中是小写的就像你在本书中看到的。 在一些特殊的场合,我们使用大写的字母,使用大写字母通常是为了显示出有一些特别的东西与这个变量相关。当一个
变量的名字有超过一个单词,有人说 $underscores_are_cool,但是其它的说$giveMeInitialCaps.,仅仅看个人的习惯。
当然, 选一个好的或者可怜的名字对于perl来说没有什么区别,你可以命名你的三个最重要的变量为:$000000000,$00000000 和$0000000000,perl 不会觉得麻烦,这时,不要请我们维护你的代码。
2.4.2 scalar 赋值
对于scalar 变量最常见的操作就是赋值,就是给变量一个值的方法。Perl中赋值的操作符就是等号(像其它的语言)。写一个变量的名字在左边,在等号的右边给出表达式的值。
$fred = 17; #给$fred 赋值 17
$barney = 'hello'; # give $barney the five-character string 'hello'
$barney = $fred + 3; # give $barney the current value of $fred plus 3 (20)
$barney = $barney * 2; # $barney is now $barney multiplied by 2 (40)
注意 最后一行使用了 $barney 两次:一次为了得到它的值,(在等号的右边)一次用来定义计算表达式的结果在哪里存放(在等号的左边)。这样是合法的,安全的和通用的。
表达式 $fred = $fred + 5(同一个变量在表达式两侧出现两次)经常在perl中出现(就像c和 java )有一个简短的写法:
$fred = $fred + 5; # without the binary assignment operator
$fred += 5; # with the binary assignment operator
下边两个也是等价的:
$barney = $barney * 3;
$barney *= 3;
另一个通用的赋值运算符是由字符串接续符组成的(.):
$str = $str . " "; # append a space to $str
$str .= " "; # same thing with assignment operator
几乎所有的二进制运算符都有简化的写法,例如:
**=.$fred **=3 意思是求$fred的立方,把结果放回到$fred.
- Learning Perl,4th Edition(2-4 scalar variables)
- Learning Perl: 2.4. Scalar Variables
- Learning Perl,4th Edition(2-2 字符串)
- Learning Perl, 4th Edition(2 绪论)
- Learning Perl, 4th Edition(2-1 数字)
- Learning Perl,4th Edition(2-3 内建警告)
- Learning Perl(4th edition)笔记<东南大学影印版>
- Learning Perl, 5th Edition [ILLUSTRATED]
- Perl Learning 1 Scalar Data
- MySQL (4th Edition)
- Algorithm 4th edition
- Learning Perl: 3.7. Scalar and List Context
- Learning Perl: 4.10. Non-Scalar Return Values
- C++ Primer (4th Edition)
- Beginning XML, 4th Edition
- 《C++ Primer》 4th Edition
- Sendmail, 4th Edition [ILLUSTRATED]
- Learning Perl: 4.5. Private Variables in Subroutines
- 浮点数到整数的快速转换
- 石头在上
- Relevance Reviews #1: The JavaScript Anthology
- translate
- translate
- Learning Perl,4th Edition(2-4 scalar variables)
- translate
- 必须掌握的8个DOS网络命令
- DataGrid中的高级ToolTip
- translate
- 存储session状态在SQL 服务器的数据库中Storing Session State in a SQL Server Database)
- javascript屏蔽一些系统热键
- CSS反转字符加密邮箱地址
- Relevance Reviews #2: Ajax Hacks