$name getting changed to $_

Discussion in 'Perl Misc' started by Brian, Aug 5, 2003.

  1. Brian

    Brian Guest

    I am stumped here - Can someone look at my code and tell me why my
    $name variable is being changed to what is stored in $_? Thx.

    foreach(@name) {
    if ($files[$x] ne "") {

    open SETI, $files[$x] or die "Can not open $files[$x] :$!";
    print "name after open = @name\n";
    while (<SETI>) {
    ### $name actually changes here - moved it for readability
    if ($. eq 39) {
    print "Default Input = $_\n";
    print "name after if = @name\n";
    chomp;

    /(\d.) hr (\d.)/;
    $Avg_Time[$x] = $1*60+$2;

    }
    }
    $x++;
    close SETI;
    }
    }

    Please let me know if you need any more information.
    Thx - Brian.
    Brian, Aug 5, 2003
    #1
    1. Advertising

  2. [posted & mailed]

    On 5 Aug 2003, Brian wrote:

    >I am stumped here - Can someone look at my code and tell me why my
    >$name variable is being changed to what is stored in $_? Thx.
    >
    >foreach(@name) {

    [snip]
    > while (<SETI>) {


    That's why.

    When you do a for-loop on an array like that, the variable you use to
    iterate over the array (by default, $_) is *aliased* to the element you're
    working on:

    @stuff = (1, 2, 3);
    for (@stuff) { $_ += 5 }
    print "@stuff"; # 6 7 8

    That is, changes done to $_ effect the element in the array.

    Additionally, when you use a while loop on a filehandle, if you don't
    specify a variable, $_ is used. The problem is that it's the SAME $_
    you happen to be using to iterate over your array.

    while (<FILE>)
    # is actually
    while (defined($_ = <FILE>))

    So, change at least ONE of those loops.

    for my $n (@name) { ... }

    while (my $line = <FILE>) { ... }

    like so.

    --
    Jeff Pinyan RPI Acacia Brother #734 2003 Rush Chairman
    "And I vos head of Gestapo for ten | Michael Palin (as Heinrich Bimmler)
    years. Ah! Five years! Nein! No! | in: The North Minehead Bye-Election
    Oh. Was NOT head of Gestapo AT ALL!" | (Monty Python's Flying Circus)
    Jeff 'japhy' Pinyan, Aug 5, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Fabian
    Replies:
    2
    Views:
    2,032
    Fabian
    Sep 9, 2004
  2. Newbie

    changed sql server db name

    Newbie, Jan 24, 2005, in forum: ASP .Net
    Replies:
    3
    Views:
    1,110
    Peter Chadwick (MCP)
    Jan 25, 2005
  3. Replies:
    1
    Views:
    682
    Rosanne
    Oct 11, 2005
  4. A Leon
    Replies:
    4
    Views:
    483
    A Leon
    Mar 4, 2004
  5. mxbrunet
    Replies:
    1
    Views:
    210
Loading...

Share This Page