Differences between chomp and chop in Perl

Source: Internet
Author: User
Tags chop

Chomp is used to delete line breaks.

Copy codeThe Code is as follows :#! /Usr/bin/perl
$ C = "abcde ";
Chomp ($ c );
Print "$ c \ n ";
[Root @ ak] # perl a. pl
Abcde

Chop is used to delete the last character.

Copy codeThe Code is as follows :#! /Usr/bin/perl
$ C = "abcde ";
Chop ($ c );
Print "$ c \ n ";
[Root @ ak] # perl a. pl
Abcd

Chomp and chop usage

1. chomp usage:

It acts on the variable, which contains a string. Chomp
You can remove it. This is basically all the functions it can accomplish, as shown in the following example:
$ Text = "alineoftext \ n"; # It can also be input by <STDIN>
Chomp ($ text );
# Remove the linefeed (\ n ).
It is very useful. Basically, each of your programs will use it. As you will know, this is the best way to remove the line break at the end of the string. Based on
One basic principle: Where variables need to be used, they can be replaced by a value assignment expression. We have a simpler method to use chomp. Perl first assigns
Value calculation, and then use this variable. Therefore, the most common method to use chomp is:
Chomp ($ text = <STDIN>); # Read, but not line break
$ Text = <STDIN>;
Chomp ($ text );
# Same as above, but completed in two steps
From the first glance, the method of the first combination looks more complicated. If we take the preceding two steps as an operation and read one row and then chomp, We will write the two statement methods.
It looks natural. If you think of it as an operation and read a row without line breaks, it is more appropriate to write a statement. Most Perl Processes
The sequencer uses the first method, and you should also use it.

2. Differences between chop and chomp:

The chop () function removes the last character.
To remove the chomp () function, you must first determine whether the last character is "\ n.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.