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 xyz.pl and try to run it
firstname.lastname@example.org:~$ perl xyz.pl
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.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix- June 29, 2020
- FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018