On 9/19/07, Ruprecht Helms <[EMAIL PROTECTED]> wrote:
> #!/usr/bin/perl

First off, you should use the strict and warnings pragmas.  So the
first two lines after the $! should be

use strict;
use warnings;


>
> open(CSV,"Kalkulation_Tauchsportportal.csv") || die "CSV-Datei nicht
> gefunden";
>
> $i=0;
>
> while (<CSV>)
> {
>         if($i==0)
>         {
>                 $Felder = $_;
>         }
>         else
>         {
>                 @Auftraege[$i] = $_;
>         }
>         $i++;
> }
> close(CSV);
> $Anzahl = $i - 1;

It is bad form to read in the entire file without doing any work*,
also, if you really want to do this you can just say

my ($felder, @Auftraege) = <CSV>;
my $Anzahl = @Auftraege;

> chop($Felder);

Never use chop**.  Use chomp instead.  The chop function removes the
last character.  The chomp function removes the end-of-line character
or character sequence.

> @Datenfelder = split(/,,,$Felder);

This line is just broken.  I assume you meant

my @Datenfelder = split /,/, $Felder;

This is not the best way to deal with CSV unless it is very simplistic
(what if there is a comma in one of the fields?).

> for(@Auftraege)
> {
>         @Datensatz = split(/,:,/,$_);

Do you really mean to be splitting on the string ",:,"?

>         $i = 0;
>         for(@Datensatz)

Notice how this loop does nothing the loop above didn't do: you are
operating on each line separately.  Why read them all in at once?

>         {
>                 print Auftrag "$Datenfelder[$i]: $Datensatz[$i]\n";

You never opened Auftrag.

>                 $i++;
>         }
> }
> close (Auftrag);
> print $Anzahl," Datensaetze geschrieben\n";

Your code is better written as

#!/usr/bin/perl

use strict;
use warnings;

my $file = "Kalkulation_Tauchsportportal.csv";
open my $csv, '<', $file
        or die "could not open ${file}:$!\n";

chomp(my $fields = <$csv>);
my @fields = split /,/, $fields;

open my $orders, ">", "orders.txt"
        or die "could not open orders.txt:$!\n";

my $records_processed;
while (<$csv>) {
        chomp;
        my %record;
        @[EMAIL PROTECTED] = split /,/;
        for my $field (@fields) {
                print $orders "${field}: $record{$field}\n";
        }
        print $orders "\n";
        $records_processed++;
}
print "$records_processed Datensaetze geschrieben\n";

* it is a waste of a loop and memory
** unless you know why exactly why chop is better for you situation
than chomp (it almost never is)

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to