Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Substituting white spaces with a tab changes my string into numeric value

by PerlPeer (Novice)
on Sep 20, 2012 at 02:22 UTC ( #994575=perlquestion: print w/ replies, xml ) Need Help??
PerlPeer has asked for the wisdom of the Perl Monks concerning the following question:

hi, I try to replace white spaces with tabs, but my string gets changed into a numeric value after that. I wrote the basic step as a new program to show what happens

#!/usr/bin/perl -w use strict; $_ = "CC1G_00040T0 NODE_4204_length_20667_cov_33.873905_4 3e-46" +; my $line = $_; print "$line\n"; $line = s/\s+/\t/g; print "$line\n";

when I run this, it gives the following:

CC1G_00040T0 NODE_4204_length_20667_cov_33.873905_4 3e-46

2

How can I prevent my string from becoming a numeric value?

Comment on Substituting white spaces with a tab changes my string into numeric value
Download Code
Re: Substituting white spaces with a tab changes my string into numeric value
by remiah (Hermit) on Sep 20, 2012 at 02:30 UTC

    change

    $line = s/\s+/\t/g;
    
    to
    $line =~ s/\s+/\t/g;
    

      Thanks!

Re: Substituting white spaces with a tab changes my string into numeric value
by dsheroh (Parson) on Sep 20, 2012 at 08:17 UTC
    To explain what was going on here:

    s/\s+/\t/g; is equivalent to $_ =~ s/\s+/\t/g;, so $line =~ s/\s+/\t/g; actually means $line = ($_ =~ s/\s+/\t/g); (The parentheses aren't actually necessary, but I wanted to make the precedence completely clear.)

    In scalar context, a regex match or substitution (=~) returns the number of matches found/substitutions performed, so, to finally get to where that 2 comes from, $line =~ s/\s+/\t/g; changes all the groups of whitespace in $_ into tabs and sets $line to the number of substitutions which were performed. If you look at $_, you will find that it holds the value you wanted, since $line and $_ held the same value before the substitution was performed.

      Thank you too.

      I figured that somehow I got a numerical value of the number of tabs, since when I used:

       s/\s+/\t/

      (thus without the "g") the number that was returned was 1 (instead of 2). I had no idea however, how this was caused.

      I frequently fail to recognize this kind of "equivalents". I hope this is just being new to perl.......

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://994575]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (11)
As of 2014-11-27 14:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (185 votes), past polls