130 likes | 347 Views
Perl primer. Syntax similar to C, various shell script langs. 3 basic data structures ... Retrieve line from STDIN ... Pattern matching ... Command execution, argument evaluation ... Variables within quotes ... E.g., welcome.pl. 3 basic data structures. $variable: scalar
E N D
Perl primer ... • Syntax similar to C, various shell script langs. • 3 basic data structures ... • Retrieve line from STDIN ... • Pattern matching ... • Command execution, argument evaluation ... • Variables within quotes ... • E.g., welcome.pl ...
3 basic data structures ... • $variable: scalar • @variable: array (indexed by integer; [ ]) • %variable: associative array (indexed by string; { }) • Prefix char. indicates type of element stored at index ... • No other datatypes recognized ... • Associative array %ENV: current environment vars. ...
Prefix char. indicates type of element stored at index ... • $array[0]: 1st element of @array • $array[1]: 2nd element • $array{'index_name'}: value of %array at index 'index_name' • $array{index_name}: same
No other datatypes recognized ... • Strings, integers, floating-points • Interconverted, based on context • $result = "1" + 2.3 + 54;
Associative array %ENV: current environment vars. ... • $ENV{'PATH'} • $ENV{'HOME'} • $ENV{'REMOTE_HOST'} • ...
Retrieve line from STDIN ... • $var = <> • <> alone: --> default var $_
Pattern matching ... • $var =~/pattern_to_match/ • Verify that contents of $var match specified pattern • Pull out matched subpatterns • egrep-style regular expressions
Command execution, argument evaluation ... • system("command") • Invoke subshell • Execute command • eval("expression") • Evaluate argument as Perl expression • Return result
Variables within quotes ... • Inside text surrounded by double quotes: interpolated • "\n": new line • Inside single-quoted text: ignored • E.g. ... • Backticks ==> execute command ... • print <<END ==> all text till END as double quoted • Easier to read
E.g., ... • $name = 'Haim'; • print "My name is $name."; ==> My name is Haim. • print 'My name is $name.'; ==> My name is $name. • print "My name is \n $name."; • ==> My name is • Haim.
Backticks ==> execute command ... • `date` ==> execute date • Return output • Often with chop() • Remove last newline from end of output • chop($date=`date`); # $date becomes "Tue Apr 16 1996"
E.g., welcome.pl ... #!/usr/local/bin/perl print "Content-type: text/plain","\n\n"; print "Welcome to IVPR's WWW Server!", "\n"; $remote_host = $ENV{'REMOTE_HOST'}; print "You are visiting from ", $remote_host, ". "; $uptime = `/usr/ucb/uptime`; ($load_average) = ($uptime =~ /average: ([^,]*)/); ... print "The load average on this machine is: ", $load_average, ".", "\n"; print "Happy navigating!", "\n"; exit (0);
($load_average) = ($uptime =~ /average: ([^,]*)/); ... ($load_average) = ($uptime =~ /average: ([^,]*)/)