chop Function in Perl

What is chop Function in Perl?


chop Function:

This is used to remove last character from the end of a string, or from end of every element of an array, or from every value of a hash.

Example :

#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$string = "anderson";
$chr = chop($string);
print $chr;
@arr= ("sam", "jill", "fred");
chop (@arr);
print "@arrn";
Result :

sa jil fre

In the above example, last character from "anderson" is removed, and at the same time the deleted character is stored in the variable "$chr" and printed. In the second example last character of the array elements "@arr" is removed and displayed.

Example :

#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('Tom',26,'Peter',51,'Jones', 23, 'John', 43);
$chr = chop(%name);
foreach $key (keys %name)
print "$key: $name{$key}<br/>";
Result :

John: 4
Jones: 2
Peter: 5
Tom: 2

In the above Perl example just the last character from every 'value' of each hash element is removed, then the hash is displayed.

Ask Questions

Ask Question