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
1 answer
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"
Log in to answer this question.
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!