The difference between chomp and chop in Perl _perl

Source: Internet
Author: User
Tags chop stdin

Chomp is used to remove line breaks.

Copy Code code 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 Code code as follows:

#!/usr/bin/perl
$c = "ABCDE";
Chop ($c);
print "$c \ n";
[Root@ak]# Perl a.pl
Abcd

the usage of chomp and chop

The use of 1.chomp:

It works on variables, and this variable contains strings. If there is a line break at the end of the string, chomp
Can get rid of it. This is basically all the functionality it can accomplish, as in the following example:
$text = "alineoftext\n"; #也可以由 <STDIN> Input
Chomp ($text);
#去掉换行符 (\ n).
It's very useful, and basically every program you use is going to need it. As you will know, this is the best way to get rid of line breaks at the end of a string. Based on Perl's
A basic principle: when you need to use a variable, you can use an assignment expression instead. We have a simpler way of using chomp. Perl first does the assignment
Value operation, and then use this variable. So the most common way to use Chomp is:
Chomp ($text =<stdin>); #读入, but not line breaks
$text =<stdin>;
Chomp ($text);
#同上, but it's done in two steps.
At first sight, the first combination of methods looks more complicated. If you think of the above as two-step operation, read one line and then Chomp, the method written in two sentences
It looks more natural. If you look at it as an action, and you read a line but do not include a newline character, it is more appropriate to write a statement. Because most Perl threads
The order clerk uses the first method, and you should use it as well.

The difference between 2.chop and chomp:

Chop () function, just remove the last character.
Chomp () function, it is necessary to first determine whether the last character is "\ n" before he is removed.

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.