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

Re: while loop returning numbers not strings

by blue_cowdawg (Monsignor)
on Dec 05, 2012 at 18:19 UTC ( #1007357=note: print w/ replies, xml ) Need Help??


in reply to while loop returning numbers not strings

OK took your code at face value and made some fundamental changes:

#!/usr/bin/perl use strict; while ($lines = <DATA>){ $word = split "", $lines; print $word."\n"; } print "\n\n"; exit 0; __END__ tutor teacher tinker sailor
and when I ran it got:
$ ./fix.pl Global symbol "$lines" requires explicit package name at ./fix.pl line + 5. Global symbol "$word" requires explicit package name at ./fix.pl line +6. Global symbol "$lines" requires explicit package name at ./fix.pl line + 6. Global symbol "$word" requires explicit package name at ./fix.pl line +8. Execution of ./fix.pl aborted due to compilation errors.
which is not too surprising. So the next set of changes:
#!/usr/bin/perl use strict; while (my $lines = <DATA>){ my $word = split "", $lines; print $word."\n"; } print "\n\n"; exit 0; __END__ tutor teacher tinker sailor
and now when we run it we get:
$ ./fix.pl 6 8 7 8
pretty much as you describe. So let's make another change:
#!/usr/bin/perl use strict; while (my $lines = <DATA>){ my ($word) = split "", $lines; print $word."\n"; } print "\n\n"; exit 0; __END__ tutor teacher tinker sailor
which gives us:
$ ./fix.pl t t t s
At this point I have a couple of comments to make:
  1. Remember: the function split() returns an array based on the regex designating where to split the string. In this case you pass in an empty string which causes your $lines variable to be split on every character. (was that your intention?)
  2. Without the enclosing parenthesis around $word you are using an array in a scalar context which means you are going to get the length of that array as a scalar not the value of the array itself.

Hope this helps you on your way....


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg


Comment on Re: while loop returning numbers not strings
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (16)
As of 2015-07-02 11:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (35 votes), past polls