Re: Writing to file

From: John W. Krahn (krahnj_at_acm.org)
Date: 02/02/04

  • Next message: Robin Sheat: "Re: How can be the return value from a subroutine saved in global array"
    To: beginners@perl.org
    Date: Sun, 01 Feb 2004 15:01:56 -0800
    
    

    Support wrote:
    >
    > Hi all

    Hello,

    > I have a little bit of code you may be able to help with. I load a
    > file into an array with
    >
    > foreach $lines(@database_array) {

    You should limit the scope of $lines to the foreach loop. Does $lines
    contain multiple lines or just one line? Perhaps you should name it
    $line instead.

    foreach my $line ( @database_array ) {

    > @edit_array = split(/\:/,$lines);
    > push(@member_array,[@edit_array]);

    You are assigning the list returned from split() to the array
    @edit_array and then copying that array to an anonymous array. If you
    lexically scope @edit_array to the foreach loop you can push its
    reference instead of copying it twice:

          my @edit_array = split /\:/, $line;
          push @member_array, \@edit_array;

    Or you could just copy the list directly and avoid using a named array:

          push @member_array, [ split /\:/, $line ];

    > $x++;

    Is $x used anywhere?

    > } #loop

    Or you could declare and assign to @member_array using the map function:

    my @member_array = map [ split /\:/ ], @database_array;

    > and then play around with the array a bit, then I would like to load
    > it back into the file with
    >
    > while($count<$x){
    > $newline = join("\:",$member_array[$count],[@edit_array]);
    > chomp($newline);
    > print DAT "$newline\n";
    > $count++;
    > }

    Perhaps you want something like this:

    foreach my $line ( @member_array ) {
        print DAT join ':', @$line;
        }

    Or with the map function:

    print DAT map join( ':', @$_ ), @member_array;

    John

    -- 
    use Perl;
    program
    fulfillment
    

  • Next message: Robin Sheat: "Re: How can be the return value from a subroutine saved in global array"