my $i = 1; while ( ) { my $file = ( split /\n/, $_ )[1] or next; ( $file ) = $file =~ m/"(.*?)"/ or next; $file = $i; open B, "> $file.csv" or warn( "Cannot open '$file': $!" ), next; print "[DEBUG] '$file': open ok\n"; chomp $_; print B $_; close B or warn( "Cannot close '$file': $!" ), next; print "[DEBUG] '$file': close ok\n"; $i++; }