This is our first post on Perl programming language. These two functions are useful in removing the last character of a given string, array(each element last character), hashes etc.

Before going into detail, we will see why we require chop and chomp functions. If you are aware of other languages like Shell and Python, they handle variables taken from user input very well. But Perl will take inputs from user differently. When Perl is asked to take inputs from user it will take variable content as the characters enter by users which includes even new line character in it.

Suppose try to save below code in to a file called and try to run it

print “$VAR1”

Sample output:$ perl


If you see, We never given n in above $VAR1 variable, Perl will try to take it by default. Some times it’s required to give only chars ‘vaares’ instead of ‘vaaresn’. This can be achieved by using chop or chomp functions which are used to remove last character in a given string array or hash.

The only difference between chop and chomp is that chop will remove any character which is present at the end of a given string but chomp will delete only new line and return characters from end.

Learn chop() functions with examples:

chop() function syntax:


Example1: Chopping a string/variable

perl -e ‘$VAR1=abc;chop($VAR1);print “$VAR1n”;’

Example2: Chopping a perl Array

perl -e ‘@ARR1=(abc, cde, efg);@ARR2=chop(@ARR1);print “@ARR2n@ARR1n”;’
ab cd ef

If you see @ARR1 is modified to ab cd ef and @ARR2 to store last chop char in it ie g in efg value.

Example3: Chopping perl Hash.

perl -e ‘%ages = (‘Martin’ => 28, ‘Sharon’ => 35, ‘Re’ => 29,);chop(%ages);print (values %ages)’$

If you see keys are choped of their last chars.

Note: chop function will not chop of values.

Want to know more about chop and chomp functions? use below perldoc command

perldoc -f chop
perldoc -f chomp

comment your thoughts on this.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.