Results 1 to 3 of 3

Thread: For Each Loop

  1. #1
    Join Date
    Apr 2008
    Posts
    9

    Unanswered: For Each Loop

    HI,
    I use the following code, which works, but i only have 7 lines and it prints 34 lines (repeating some). Can you help me figure out what i'm doing wrong? we sort by shelf key 13 but print the call number 14


    #!/usr/local/bin/perl -w
    $data_file="youthbooksc.txt";
    open(DAT, $data_file);

    @L=();
    %Sortbyshelfkey=();

    while(<DAT>)
    {
    chomp;

    @L=split(/\|/, $_);
    @{$Sortbyshelfkey{$L[13]}}=@L;

    foreach my $f (sort keys %Sortbyshelfkey)
    {
    print "Call #: $Sortbyshelfkey{$f}[14] \n"; #
    }

    }

  2. #2
    Join Date
    Oct 2002
    Location
    Baghdad, Iraq
    Posts
    697
    First off, it's printing 74 with reps because you're printing each time you read a line. Look at how your curly braces are nested.

    To make your code a little easier to debug, use some lexicals and use strict.

    I don't have the actual data, but try these general changes:

    Code:
    use strict;
    
    my $data_file="youthbooksc.txt";
    open(my $dat, $data_file);
    
    my(%Sortbyshelfkey);
    
    while(<$dat>)
    {
    chomp;
     # No reason to declare @L outside the scope that it's actually used.
    my(@L)=split(/\|/, $_);
    # This does the same thing your code did but makes it clear that 
    # you're creating a reference to an anonymous array.
    $Sortbyshelfkey{$L[13]}=[@L];
    }
    
    foreach my $f (sort keys %Sortbyshelfkey)
    {
        print "Call #: $Sortbyshelfkey{$f}->[14]  \n"; 
    # And this makes it clear that you're dereferencing that array.
    }

  3. #3
    Join Date
    Apr 2008
    Posts
    9
    thanks,
    yes, it wasn't so much repeating as starting with 1st line, then 2nd line (with the new one sorted), 3rd line etc.

    thats solves it.
    -mw

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •