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

Yet another array problem

by Angharad (Pilgrim)
on Jul 29, 2005 at 15:14 UTC ( [id://479437]=perlquestion: print w/replies, xml ) Need Help??

Angharad has asked for the wisdom of the Perl Monks concerning the following question:

Hi there again :)
I was wondering why this doesnt work. I have an array of numbers. I use a while loop as follows to split the array.
while(<>) { @array = $_; @array = split; }
This splits the array via new line. Every element of the array holds a string of numbers. The element $array[0] for example might contain the following data.
12 44 111 445
The numbers are separated by tabs.
I now want to get at individual numbers from the element $array[0]. So, I attempted the following.
@line1 = $array[0]; print "@line1\n"; # this works @line1 = split(/\t/); $var1 = $line1[0]; print "$var1\n"; # this doesnt work
$var1 doesnt print. Could anyone please tell me why and what I could try to rectify this? Thanks

Replies are listed 'Best First'.
Re: Yet another array problem
by davorg (Chancellor) on Jul 29, 2005 at 15:20 UTC

    Your description of what you are trying to do isn't very clear, but I think you're trying to build a two-dimensional array. If that's the case then you should probably read perllol. If not, then you should probably have another go at describing your problem.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Yet another array problem
by pbeckingham (Parson) on Jul 29, 2005 at 15:19 UTC

    Well... The first line inside the loop is redundant, as you assign a string to an array, then overwrite that same array.

    Your code below is laso relying on $_ in cases where there is no value.

    Consider this:

    while (<>) { for (/(\d+)/g) { print $_, "\n"; } }



    pbeckingham - typist, perishable vertebrate.
Re: Yet another array problem
by kwaping (Priest) on Jul 29, 2005 at 15:29 UTC
    I generally try to avoid operating on @_ and $_ wherever possible, to avoid confusion and pitfalls like what you may be experiencing. Here's some code I whipped up that I think does the operation you desire but in a slightly different way.
    #!/usr/bin/perl use strict; use warnings; my $var = ''; my @array = (); foreach my $line (<DATA>) { chomp $line; @array = split(/\t/,$line); $var = $array[0]; #<- not necessary, but wanted to mimic OP's code print "$var\n"; } exit; __DATA__ 1 4 8 9 23 432 23 21 98 87 4 32
    Does that help any?
      I generally try to avoid operating on @_ and $_ wherever possible, to avoid confusion and pitfalls like what you may be experiencing.
      @_ and $_ are idiomatic of Perl. The former is much a Perl5 thing, but the latter will also be there in Perl6, more powerful than ever! Their use can be confusing only to non-perl programmers trying to hack at Perl. Also, while you can avoid "operating" on $_ (but only if you want to make your life more complicated than necessary!), @_ is the only means to pass parameters to subs, so you can't avoid to "operate" on it. Or do you prefer to clobber your main namespace of global variables?
      Here's some code I whipped up that I think does the operation you desire but in a slightly different way.
      #!/usr/bin/perl use strict; use warnings;
      Good!
      my $var = ''; my @array = ();
      No need for the initializations.
      foreach my $line (<DATA>) {
      While this does work, it is generally advised against as an extremely bad habit as it will slurp in the whole file at a time. Sometimes it doesn't make much harm, sometimes it is necessary, but it is not here and it would be recommendable not to spread bad programming habits amongst newbies.
      exit;
      No need whatsoever for this!
        1. I think you're reading too much into my statement about @_ and $_. My point was really that using named variables is usually more clear (to me at least) than using no variable, relying in the default of either $_ or @_ in the function. Call it TIMTOWDI, call it style, but that's how I do it.

        Oh, and I definitely am NOT a "non-Perl programmer trying to hack at Perl". I've been coding Perl for 10 years now. It was my first programming language and remains my primary language to this day. Don't assume noobness just because someone's coding style is different than yours.

        2. Thank you. Old habit.

        3. There is need for the declarations under the strict pragma. I initialize when I declare as a matter of habit, to avoid "uninitialized" warnings. I also like giving all variables default values as another matter of personal style.

        4. I wasnt aware that line wasn't blazar-approved. I'll stop using it immediately. :) Seriously though, my coding style is situational. Since DATA is tiny in this case, I used that style. If you have a recommendation for the "newbies", you might want to actually write out some alternate code instead of just calling mine wrong and leaving it at that. That doesn't help anyone, does it?

        5. Again, old habit. It does no harm except take an extra quarter-second to type.
      Thank you. I will try that.
Re: Yet another array problem
by 5mi11er (Deacon) on Jul 29, 2005 at 16:30 UTC
    From the line immediately following your commented line "#this works", you attempt to overwrite your array @line1 by splitting the numbers out of @line1, except you've forgotten to specify that you want it to operate on @line1, so instead it's operating on $_.

    So, not only is it operating on the wrong variable, it also destroys the array that had the correct information. Overwriting variables like this is not generally a good idea.

    If you don't need the intermediate result learn how to chain the operations together, or how to dereference things correctly. I'd suggest placing the data read from the file into a two dimensional array as you're reading it in, rather than keeping the lines as they were read, and then later attempting to split everything out.

    -Scott

      Thanks for the tip.
Re: Yet another array problem
by blazar (Canon) on Jul 29, 2005 at 15:35 UTC
    I was wondering why this doesnt work. I have an array of numbers. I use a while loop as follows to split the array.
    while(<>) { @array = $_; @array = split; }
    The description of your problem doesn't match the code sample you give. You don't have an "array of numbers". You have an array to which you're assigning twice for every while loop, reading from a file. You're not "splitting the array". You're splitting line of text into an array. Only the data coming out of the last line of text will be there ater the loop. Oh, and the first assignment does nothing at all.
    This splits the array via new line. Every element of the array holds a string of numbers. The element $array0 for example might contain the following data.
    12 44 111 445
    No, it may not! Incidentally, if you use square parens either use html entities or enclose in code tags as appropriate: [whatever] has a special meaning to PM.

    As another poster suggested to you, you be looking after a bidimensional array. I suggest you first read some introductory tutorial to Perl, though.

Re: Yet another array problem
by tlm (Prior) on Jul 29, 2005 at 15:55 UTC

    I was wondering why this doesnt work.

    Learning Perl (or any other computer language) by sheer trial and error is a very inefficient process. In the immortal words of Dominus, "you can't just make shit up and expect the computer to magically know what you mean". Rather than posting questions like this, get yourself a decent Perl book, and study it.

    the lowliest monk

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-16 17:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found