美文网首页
Learn Perl #1

Learn Perl #1

作者: Sicuso | 来源:发表于2016-02-07 19:16 被阅读13次

Perl

use strict & warnings

#!/usr/bin/perl
use strict;
use warnings;

A potential problem caught by use strict; will cause your code to stop immediately when it is encountered, while use warnings; will merely give a warning (like the command-line switch -w) and let your code run.

print '' & ""

 print "Hello, $name\n";     # works fine
 print 'Hello, $name\n';     # prints $name\n literally

variables

scalars

A scalar represents a single value:

Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required.

 my $animal = "camel";
 my $answer = 42;

==note==

print; # prints contents of $_ by default

Arrays

An array represents a list of values

Arrays are zero-indexed.

 my @animals = ("camel", "llama", "owl");
 my @numbers = (23, 42, 69);
 my @mixed   = ("camel", 42, 1.23);

@animals[0,1];                 # gives ("camel", "llama");
@animals[0..2];                # gives ("camel", "llama", "owl");
@animals[1..$#animals];        # gives all except the first element

==note==

$#array tells you the index of the last element of an array:

Hashes

A hash represents a set of key/value pairs:

 my %fruit_color = ("apple", "red", "banana", "yellow");

You can use whitespace and the => operator to lay them out more nicely:

 my %fruit_color = (
    apple  => "red",
    banana => "yellow",
 );

To get at hash elements:

$fruit_color{"apple"};   

You can get at lists of keys and values with keys() and values().

my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;

Variable scoping

However, the above usage will create global variables throughout your program, which is bad programming practice. my creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined

 my $x = "foo";
 my $some_condition = 1;
 if ($some_condition) {
     my $y = "bar";
     print $x;           # prints "foo"
     print $y;           # prints "bar"
 }
 print $x;               # prints "foo"
 print $y;               # prints nothing; $y has fallen out of scope

Regexp

  • =~ match
  • !~ does not match

Replace

s/<pattern>;/<replacement>;/

match

m/<regexp>;/ or /<regexp>;/

transform

tr/<pattern>;/<replacemnt>;/

相关文章

网友评论

      本文标题:Learn Perl #1

      本文链接:https://www.haomeiwen.com/subject/gkeykttx.html