Friday, March 9, 2012

Perl: Variables and Functions

I have written Perl scripts for a long time (around 3 years?). However, since my programming style is so mixed: Perl, Matlab, C, Fortran, Mathematica, and their concept/syntax confuse me after not using it for some time. Here I summarize how the variables and functions are used.


Variables: Scalar, Arrays, Hash (not used much)

1. Scalar
    Define:  $variable
    Access:  $variable

2. Array
    Define:  @variable
    Access:  For each element, $variable[0]; to get the whole array @variable


Functions: define function, function input, function return

1. Define a Function: use sub to define, use & to call the function

#! /usr/bin/perl -w
use strict;

sub TestPrint{
    return "Test and Print\n";
}

&TestPrint;

2. Reference: similar as pointer in C, it is often used to pass value into/out of subroutine.




Subroutine take zero or more scalar arguments as input (and possibly output), and they return zero or one scalar as a return value.

2. Function Input: the @_ is input arguments, better to first convert it into private variables

#! /usr/bin/perl -w
use strict;

sub TestPrint {
   my($test1, @test2) = @_;
   my $test_print;

   foreach my $test_tmp (@test2) {
       $test_print .= "$test1, $test_tmp!\n";
   }

   print "$test_print\n";
}

my @name;

$name[0] = "Pan";
$name[1] = "Yue";
$name[2] = "TinTin";

&TestPrint("Hi", @name);
&TestPrint("Hi", "Pan", "Yue", "TinTin");


3. Function Return: return can be scaler, arrays or hash, better to use explicitly "return"







No comments:

Post a Comment