PERL tutorial' from Unix Perspective

Unix OS - Lecture 7
   An introduction to perl
   now used for:
     system administration
     client-server programming
     database access
   many modules like CGI,DBI and LWP,Tk
   perl -d program args # this is debugging mode
   perl -de 0 #interactive to test statements
   #!/usr/bin/perl -w #-w issues warnings
   
   there are three data structures
    --scalars
    --arrays
    --associateive arrays, known as "hashes"
   you could dnamically add the new value to array;
   $#days is the last index of array @days;
   arrays are indexed by numbers , starting with 0
   hash are index by string;
   print @arrays[3,4,5]
   print %hash{'a','c'}
   print  @arrays
   print    %hash
   $foo and @foo are two different variables;#each variable type has its own namespace
   range .. operator like <print 1..9>
   concatenation operatpr of "." like print "hello"." world"
   string repertitor of x; print "fred"*3
    <==/eq> is comparision of <number/string>
    !=/ne
    </lt
    >/gt
    <=/le
    >=ge
    pattern matching
    if($var =~ m/pattern/){...}
    if($var !~ m/pattern/){...}
   substitution
    $var1 =~ s/pattern/replacement;
   chop($var) will takes a single argument and remove the last character from the string value
   chmop($var) will remove only a newline charracter at the end if there is one;
   <$a = <STDIN>;chomp($a)> equals <chomp($a=<STDIN>)>
   @barney=@fred;
   $length=@arr; //will get the length number of the arr.
   undef is returned when accessing an array element beyond the end of the current array
   when arrays are used as a stack of information'
    push(@mylist,$newvalue) like @mylist=(@mylist,$newvalue)
    $oldvalue=pop(@mylist)
   shift and unshift will perform from the left side of a list;
    unshift(@mylist,$value) like @mylist=($value,@mylist,)
    $x=shift(@mylist)
    
   
   one note for chomp:
   
     reverse and sort functions for arraylist;
     {
     @stuff=("haha\n","heihei\n")
     chomp(@stuff) will get ("haha","heihei")
     }
     
   grep method from perl
     @toys=qw(aa bb cc dd aac aaj)
     @cars=grep(/aa/,@toys) will get aa, aac, aaj 
     @daemons = grep /daemon/, `ps -ef`;
   
   Iterating through an array:
     c=stype for loop
       for($I=0;$I<@myarray;$I++){}
     foreach loop
       foreach $element(@myarray){}
       
   @a=<STDIN>, in thie context, <STDIN> returns all remaining lines up to the end of a fuile;
   each line is returned as a seperarate element of the list;
   
   @ARGV Array:
   
      @ARGV contains command line arguments and does not include a prormam name
      $0 contains program name
      if(@ARGV != 2){ die: "usage: $0 infile arg\n"}
   Hash functions:
   
       %carcolor = {
       buick =>'yellow'
       }
       keys(%hashname) will yield a list of the current keys;
       foreach $key(keys(%fred))
       special %ENV hash stores enviroment variables
       print $ENV{"SHELL"}
       @lastname=valuse(%lastname)
       while(($first,$last)=each(%lastname) //return a key-value pair as a two element list;
       delete $lastname{"barney"}
       if($emp{john}) //checking for a true/false value
       if(exists $emp{join}) //checking for an existing key
       if(defined $emp{john})
       if(%emp) to check if contains anything;
     Foreach example
       @numbers=(1,2,3)
       foreach $one(@numbers)
       {
       $one*=3;
       }
       then @numbers is now(3,6,9);
     perl uses the variable $_ to contain the line read from STDIN.
     $a=<STDIN>;
     @a=<STDIN>;
     while(defined($line=<STDIN>)){} when no more lines read, <STDIN> returns undef.
   
     using the diamond operatpr<>
      <> operators like <STDIN> but gets data from file or files;
      specified on the command line that invoked the perl programme
      <> lool at the @ARGV array;
      #!/usr/bin/perl
      while(<>)
      {
      print $_;
      }
   perl supports the same regular expressions as in SED , =~
   regular expressions:
     split function takes a regular expression and a string
     split(/:/, $line)
     $outline=join(":",@fields)
   PERL functions:
   
      sub subname
      {
      }
      return value is the value for the  return statement for of the last expression evaluated in the subroutine
      $var=myroutine(parameters);
      @array=myroutine(parameters);
      
      @_ for the duration of the subroutine
      $_[0] is the first element of the @_
      @_ variable is private to the subroutine
      
      sub add
      {
      my ($sum);make it a local variable,
      foreach $_(@_)
      {
      $sum+=$-
      }
      return $sum;
      }
   
      //semi private variable is named <local>, <my> is private variable; use strict
      http://bbs.chinaunix.net/thread-1701085-1-1.html
        perl local my our 的前世今生;
      http://www.tutorialspoint.com/perl/perl_modules.htm
        Writing PERL Modules;
      will ask the declaration or the package name as the prefix;
      programmer may choose to require declarions by <use strict> or <use strict 'vars'>
      
   
   
   
Unix OS - Lecture 8

    Functions:arguments
      passing arrays$core=average(@maths,@English)
      passing references to arrays
      passing hashes%checks=payroll(%emp)
      passing references to hashes
      
    Signal handling
      special hash %SIG used for signal handling
      hash keys are the signal names
       e.g. SIGCHLD,HUP
      hash values are the signal decisions
       ignore signals:
       $SIG{INT}='IGNORE'
       reset the default
       $SIG{INT}='default'
       catching signals
       $SIG{INT} = \&mycatch
    Recommanding use all uppercase letters in your file handles
       STDIN
       STDOUT
       STDERR
       open(FILEHANDLE,">filename")||die "sorry could not open"//open for writing to a file;
       open(FILEHANDLE,"filename")//open for reading;
       print FILEHANDLE "hello"
       perl provide <-op> file test
       
    Executing Unix commands from a PERL script
       $var=`who`
       @output=`who`
       $status = system("who")
       
    Reading and Openning Directory files(perl cookbook)
       $dir = "/d/d1/d2"
       opendir DH, $dir or die "cant not open $dir:$!"//$! is used to get the system error message
       while (defined($filename=readdir DH))
       {
       print "$filename\n";
       }
       @files= readdir DH; //get a array containing all the files;
       closedir DH
       rewinddir DH
    http://stackoverflow.com/questions/6534573/whats-the-difference-between-exists-and-defined
    
      What's the difference between exists and defined?
    http://stackoverflow.com/questions/3402821/in-perl-what-is-the-difference-between-a-pm-perl-module-and-pl-perl-script
      sub new { bless {} => shift }
      sub something { print "something\n" }
      
    http://www.kichwa.com/quik_ref/spec_variables.html
    
       $!  If used in a numeric context, yields the current value of errno, with all the usual caveats.
       (This means that you shouldn't depend on the value of $! to be anything in particular unless you've gotten a specific error return
       indicating a system error.) If used in a string context, yields the corresponding sysem error string.  What just went bang?
       
    http://stackoverflow.com/questions/6534573/whats-the-difference-between-exists-and-defined
      
       This is well-documented in the perldoc entries for defined and exists. Here's a quick summary:

       defined $hash{key} tells you whether or not the value for the given key is defined (i.e. not undef). Use it to distinguish between undefined values and values that are false in a boolean context such as 0 and ''.

       exists $hash{key} tells you whether or not %hash contains the given key. Use it to distinguish between undefined values and non-existent ones.

       This is easiest to see with an example. Given this hash:

       my %hash = (a => 1, b => 0, c => undef);
       Here are the results for retrieval, defined-ness, and existence:

       # key  value  defined  exists
       a          1        1       1
       b          0        1       1
       c      undef        0       1
       d      undef        0       0
       In practice, people often write just if ($hash{key}) {...} because (in many common cases) only true values are meaningful/possible. If false values are valid you must add defined() to the test. exists() is used much less often. The most common case is probably when using a hash as a set. e.g.

       my %set = map { $_ => undef } 'a' .. 'z';
       Using undef for set values has a few advantages:

       It more accurately represents the intent (only the keys are meaningful, not the values).
       All undef values share a single allocation (which saves memory).
       exists() tests are slightly faster (because Perl doesn't have to retrieve the value, only determine that there is one).
       It also has the disadvantage that you have to use exists() to check for set membership, which requires more typing and will do the wrong thing if you forget it.

       Another place where exists is useful is to probe locked hashes before attempting to retrieve a value (which would trigger an exception).
       
       
       

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值