ACCC Home Page ACADEMIC COMPUTING and COMMUNICATIONS CENTER
Accounts / Passwords Email Labs / Classrooms Telecom Software Computing and Network Services Education / Teaching Getting Help
 
Seminar - Perl II
0. Contents 1. Intro 2. Sources 3. Special Variables 4. Subroutines 5. Regexp
6. Ties & DBM 7. Functions 8. Eval 9. Larger Example 10. Exercises  

Special Variables

   
 
     
@ARGV
 

  • The command line arguments are passed in @ARGV
  • The default for shift is @ARGV in the main program.
  • The input operator <> works on the files named in @ARGV by default.
 
     
@_
 

  • @_ is the array used to pass arguments to subroutines.
  • The default for shift is @_ within a subroutine.
 
     
$_
  $_ is the default scalar argument for many operators. For example:
  foreach (@array) {
      print if /A/;
  }
is really the same as:
  foreach $_ (@array) {
      print $_ if ($_ =~ /A/);
  }
So $_ is used most often when it isn't seen. Some operators that use $_ as default are foreach, grep, map, print, chop.
 
     
$/
 

$/ is the string that separates lines when read with the <> operator. Remember that in scalar context, <F> reads one line from the filehandle F. What constitutes a line? Whatever ends with $/. By default this is a newline, but you can set $/ to anything. In fact, if you set it to undef, you will then slurp in the whole file in scalar mode.

 
     
$!
 

$! is set to an error message if a preceeding opeartion fails. Often used with die to report errors.

    open (F, "filename") or die "Can't open filename: $!";
 
     
$@
 

$@ is set to a non-null error message if eval fails. Very useful for trapping exceptions.

    eval {$some_code};
    if ($@) {
	print STDERR "eval failed: $@\n";
    }
 
     
Others
 

There are all sorts of other special variables, such as $| that set output buffering, or $$ that contains the current pid. But the above are the most useful to be aware of.

 
 

Perl II Previous: 2. Sources Next: 4. Subroutines


1999-6-15  BobG
UIC Home Page Search UIC Pages Contact UIC