Learn Perl #1

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>;/

    原文作者:Sicuso
    原文地址: https://www.jianshu.com/p/7c3159ea84a4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞