Perl 入门

1,初识 Perl

2,数据类型

3,标量:字符串

4,数组

1, 初识 Perl

#!/usr/bin/perl

print "Hello World!\n"

2, 数据类型

  • 标量可以是数字,字符串,浮点数。使用时,在变量的名字前面加上一个"$",表示标量;
  • 数组变量以字符 @ 开头,索引从 0 开始;
  • 哈希(也称为关联数组)变量以字符 % 开头,是一个无序的 key/value 集合。
#!/usr/bin/perl

# 标量示例:
$a = 1.25;
$b = 255.0;

$c = $a + $b;

print "标量示例:";
print $c;

# 数组示例:
@books = ("Perl", "Shell", "Java", "C++");

print "数组示例:\n";
print "\$books[0] = $books[0]\n";
print "\$books[1] = $books[1]\n";
print "\$books[2] = $books[2]\n";
print "\$books[3] = $books[3]\n";

# 哈希示例:
%prices = ("Perl", 20, "Shell", 15, "Java", 100, "C++", 200);

print "哈希示例:\n";
print "\$prices{\"Perl\"} = $prices{\"Perl\"}\n";
print "\$prices{\"Shell\"} = $prices{\"Shell\"}\n";
print "\$prices{\"Java\"} = $prices{\"Java\"}\n";
print "\$prices{\"C++\"} = $prices{\"C++\"}\n";

3. 标量:字符串

3.1 单引号和双引号区别

  • Perl 不会解析单引号中的内容,但会解析双引号中的内容。
# 示例一:转义字符

#     单引号除了 \' 和 \\ 之外的转义字符,单引号内的所有字符都代表它们自己;
perl -e "print 'Hello world \t\n'"
perl -e "print \"Hello world \t\n \" "

# 示例二:变量
#!/usr/bin/perl

$string = "world";

print ' hello $string';

print "\n hello $string";

3.2 操作符:.x

# . 操作符:用于连接字符串
#!/usr/bin/perl

$score = 98;

print "你的考试分数是:" . $score . "分";


# x 操作符:表示字符串重复操作
#!/usr/bin/perl

my $string = "china " x 3;

print $string . "\n";

3.3 chomp 函数

# 示例一:未使用 chomp 函数
#!/usr/bin/perl

print "Please input an string and a number by order!\n";

$the_string=<>;
$the_num=<>;

print "The result is\n";
print "$the_string" x "$the_num";


# 示例二:使用 chomp 函数
#!/usr/bin/perl

print "Please input an string and a number by order!\n";

chomp($the_string=<>);
chomp($the_num=<>);

print "The result is\n";
print "$the_string" x "$the_num";

4. 数组

# 创建数组的两种方式
# 方式一:
@friends = ("小明","小张","小李");

# 方式二:
@apps = qw/google facebook twitter/;

参考资料: