Monday, October 18, 2010

String Manipulating functions in PERL

In every programming languages the string type variables are subjected to rigorous experiments by the programmers. Sorting, Splitting, Pattern matching, Concatenating, Modifying etc. PERL provides some instant functions for the manipulation of the strings. Some of them are listed below:

1: chop(string):
This will remove the last character from a string variable. It is also used in removing the escape character from the value being entered. For example:

 chop("GOOD") results in a word "GOO";

2: crypt(string,salt)
The crypt function encrypts a string using the NBS Data Encryption Standard (DES) algorithm. The salt is of a two character string. It can be Numbers, Alphabets etc.
The syntax for the crypt function is as follows:

result = crypt (original, salt);

3: grep
The grep function provides a convenient way of extracting the elements of a list that match a specified pattern. (Same as that  of Unix.) The syntax for the grep function is array = grep (pattern, searchlist);
For example:

@list = ("This", "is", "a", "test");

@array = grep(/^[tT]/, @list);

This will be forming a new array of list in which contains the words that have the t or T

4: splice
 This function will helps to replace the values in the array at specified positions. The usage is as follows

@array = ("1", "2", "3", "4");

splice (@array, 1, 2, ("two", "three"));

The modified array will  have the following contents:

("1", "two", "three", "4") : replaced the values at the index of 1 and 2

5: push
This will helps to push a new element to the end of the list . The usage of this function is as follows:

push(@array,"new");

This will add the new element "new" to the end of the @array

6:pop
This will remove the last element form the array. The usage is similar to that of the function pop.

7:split
This function is extensively used in perl for splitting the string supplied with a specific pattern in to a list of strings with the pattern. The usage of this function is as follows. Suppose the string is

$line = "This:is:a:string";

applying the split function

@list = split (/:/, $line);

The array @list contains the elements "This", "is", "a", "string"

There are many other functions for manipulating the lists based on the pattern matching. These functions provide more convinient for the programmers to use the datastructures.

No comments:

Post a Comment