Re: Re: trying to learn
Ritesh Raj Sarraf <[email protected]> Fri, 3 Sep 2004 15:56:47 +0545 (NPT)
| Newsgroups | gmane.user-groups.linux.delhi.devel |
|---|---|
| Message-ID | <[email protected]> |
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Fri, 3 Sep 2004, Abhijit Menon-Sen wrote: > At 2004-09-03 12:15:25 +0545, [email protected] wrote: >> >> In the for loop I want my new array name to be assigned at runtime >> like @line1, @line2 and so.. > > Whenever you find yourself wanting to name variables "@line1, @line2 and > so on", step back and ask yourself why you aren't using an array, which > gives you variables "named" $line[1], $line[2], and so on. > $line[1] would refer to a single scalar variable which is the second element of array @line. Since, @line = <STDIN>; would contain 3 elements if the following would be what I typed. 23 34 6545 32 2543 "Enter Key" # The first enter key 76 354 394875 9834 "Enter Key" # The second enter key 435 567 876 345 587 "Enter Key" # The third enter key CTRL + D # Finish the input. What I understand is that at this point @line would be having three elements each with a new line character at the end. >> @numbers = <STDIN>; >> >> @all_lines = split(/\n/, @numbers); > Since I don't know how many lines of input can be there in the array, how will i break/split them and move to other arrays. That's why I was thinking of a way of dynamic array naming :-) But as you say,, I've already mistaken. > This is wrong. > > For starters, split works on strings, not numbers. Your @numbers already > contains what you want to put in @all_lines. But, apart from that, since > you want to operate on each line separately, why not do so directly? > > $i = 0; > $total = 0; > @lines = (); > > while ( $numbers = <STDIN> ) { > # $sum = sum of the numbers in $numbers > > $lines[$i++] = $sum; > $total += $sum; > } > > To find the sum of one line, you will need to use split / /. > > -- ams > The above code looks really what I wanted. But i might have to add a check on $numbers to see if the user input just a single number or multiple numbers separated by spaces.. Right ???? rrs - -- Ritesh Raj Sarraf RESEARCHUT -- http://www.researchut.com Gnupg Key ID: 04F130BC "Stealing logic from one person is plagiarism, stealing from many is research". -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Made with pgp4pine 1.76 iD8DBQFBOENq4Rhi6gTxMLwRAvWgAKCHZtfO0opXctHlesIyxcL2bN6w2gCfb1k+ v+5rk93jmbhVNfQg7awg6n4= =42TB -----END PGP SIGNATURE-----