sans-clue has asked for the wisdom of the Perl Monks concerning the following question:

If I have have loop that is working like this
foreach $lyne (@lines){ printf $lyne\n; }
I need to have each 'lyne' output to an individual file
like you would in shell if you did
set RANDOM x=$RANDOM for lyne in `cat somefile (assume no spaces)` ; do echo $lyne > prefix$x.txt x=`expr $x + 1` done

What would be the most efficient way to do this, outputting a file on windows ?
Thanks

Replies are listed 'Best First'.
Re: print line to file on win32
by halley (Prior) on Oct 29, 2007 at 18:21 UTC
    Your first example isn't working, as you've forgotten some quotes around the string to print. The second example isn't much better as you're not setting RANDOM to anything in particular to begin. It seems a bit weird to generate a lot of one-line output files. This doesn't instill confidence that you're asking the right questions, but if I can guess at your intent:
    $x = int(rand(65535)); my $in; open($in, '<', "somefile") or die $!; for $line (<$in>) { my $out; open($out, '>', "prefix$x.txt") or die $!; print $out $line; $x++; }

    Update:: Changed to work exactly like the shell version (as far as I can tell without being arsed to test it). Didn't try to optimize it or golf it further, so you can see the relative syntaxes involved.

    And this has nothing to do with Win32, by the way.

    --
    [ e d @ h a l l e y . c c ]

      Thanks, this is what I needed
      my $out; open($out, '>', "prefix$x.txt") or die $!; print $out $line; $x++;

      work great now. Why ? Perl is great at not placing a filehandle on a log file on win32 that I am tailing, but I have a vbscript that has to process each line. It is a looping vbscript, and I don't want to fork it for each line, rather have it loop picking up lines/files. Thanks

        Perl is great at not placing a filehandle on a log file on win32

        Could you please explain what this means? We can probably help you fix your real problem instead of your hack.

Re: print line to file on win32
by ikegami (Patriarch) on Oct 29, 2007 at 18:24 UTC

    Something like this?

    my $x = rand(65536); foreach (@lines) { open(my $fh_out, '>', sprintf('prefix%04X.txt', $x)) or die; print $fh_out $_; $x = ($x + 1) % 65536; }

    I'm not sure how useful it is to start at a random number if you only increment afterwards.

    Update: Ah! you're not refering to the variable named $RANDOM that exists in some shells. You're refering to some randomly named variable.

    my $x = 0; foreach (@lines) { open(my $fh_out, '>', sprintf('prefix.%04d.txt', $x++)) or die; print $fh_out $_; }

    Or if you are reading from file handle,

    while (<$fh_in>) { open(my $fh, '>', sprintf('prefix.%04d.txt', $.)) or die; print $fh_out $_; }
Re: print line to file on win32
by moritz (Cardinal) on Oct 29, 2007 at 18:23 UTC