Question: (Closed) Perl Code: Difference between print and print $_
1
gravatar for Shicheng Guo
3.6 years ago by
Shicheng Guo7.5k
Shicheng Guo7.5k wrote:

 

Suppose the contents of the a.fa is as the following: 

> a b c

> d_b c.m

the following code were used to remove the space of the head line in a.fa. What's difference between these two script? and Why? 

 perl -lane "s/\s+/_/g if /^>/; print " a.fa

 perl -lane "s/\s+/_/g if /^>/; print $_" a.fa

 

print perl • 910 views
ADD COMMENTlink modified 3.6 years ago • written 3.6 years ago by Shicheng Guo7.5k
2

Hello Shicheng Guo!

We believe that this post does not fit the main topic of this site.

not a bioinformatics question but general perl programming, this smells like homework too.

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

ADD REPLYlink modified 3.6 years ago • written 3.6 years ago by Michael Dondrup46k
1
gravatar for Manuel Landesfeind
3.6 years ago by
Göttingen, Germany
Manuel Landesfeind1.2k wrote:

I think, the intention is not to have a difference. However, when executing your second line of code in BASH, you have to escape the dollar symbol, like this:

perl -lane "s/\s+/_/g if /^>/; print \$_ "

or use single quotes like so:

perl -lane 's/\s+/_/g if /^>/; print $_'

If used correctly, the output of both commands is the same. This is due to Perl print's implementation: "If LIST is omitted, prints $_ to the currently selected output handle." Which means that without further selection of the filehandle to use, print() without any argument will write the content of $_ to the standard output. The same applies for a large number of built-in functions including regular expressions like `s///` which also use $_ if no other variable is given. Thus, the following to lines of code are equivalent:

      s/\s+/_/g;
$_ =~ s/\s+/_/g;

A general note: using perlvar short forms in Perl software does not only make the code harder to read and to understand but can easily introduce errors. From my point of view, a nice rule of thumb is: "If you have to use it explicitly, use something else instead"

ADD COMMENTlink written 3.6 years ago by Manuel Landesfeind1.2k
Please log in to add an answer.
The thread is closed. No new answers may be added.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1552 users visited in the last hour