Wednesday, February 17, 2010

Perl Hash examples

Example:

    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    %name = ('Tom',26,'Peter',51,'Jones', 23, 'John', 43);
    print "Sorted by Keys \n
";
    foreach $key (sort keys %name)
    {
      print "$key: $name{$key}
";
    }
    print "Sorted by Values \n
";
    foreach $value (sort {$name{$a} cmp $name{$b} }keys %name)
    {
      print "$value: $name{$value}
";
    }

Result:

Sorted by Keys
     John: 43
     Jones: 23
     Peter: 51
     Tom: 26
Sorted by Values
     Jones: 23
     Tom: 26
     John: 43
     Peter: 51


Regular expressions are that makes Perl an ideal language for "Practical extraction and reporting" as the name implies.To construct the regular expression, which is essentially a sequence of characters describing the pattern you would like to match.

Metacharacter      Default Behaviour
\     Quote next character
^     Match beginning-of-string
.     Match any character except newline
$     Match end-of-string
|     Alternation
()     Grouping and save subpattern
[ ]     Character class


The split() function is used to split up a string using a regular expression delimiter or a character or a string.
Syntax:

     split (string);

In the above syntax, split() function takes a "string" as the argument.
Example to split string using regular expression delimiter:

    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    $str1 = "how,are,you";
    $str2 = "how!!are!!you";
    $str3 = "how1are2you";
    @val1 = split(",", $str1);
    @val2 = split('!!', $str2);
    @val3 = split(/\d+/, $str3);
    print "Removed the character Comma","\n";
    print "
";
    foreach $val1 (@val1)
     {
       print "$val1\n";
     }
    print "
";
    print "Removed the string '!!'";
    print "
";
    foreach $val2 (@val2)
     {
       print "$val2\n";
     }
    print "
";
    print "Removed the decimals 1,2";
    print "
";
    foreach $val3 (@val3)
     {
       print "$val3\n";
     }

Result:

    Removed the character Comma
    how are you
    Removed the string '!!'
    how are you
    Removed the decimals 1,2
    how are you

In the above example the string "howareyou" is seperated first with a comma, then by a string "!!", at last seperated by decimals "1,2", which is removed using a regular expression "/\d+/". All these strings are split and stored in an array, then using a loop its returned one by one.

No comments:

Post a Comment

Search This Blog