chinesebob has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to encrypt files and then put them someplace else. But after using Crypt::OpenPGP to encrypt them, the files are just sitting in memory as a text and I can't seem to push them to a file. If I put in print $ciphertext they appear in the log.txt file as the encrypted text. I need them in their own separate file to be moved around and so on.
Does anyone have any ideas?
See Code:
sub process_dir{ my $directory = shift; my @file = &open_directory($directory); for my $processing(@file){ my $file= &encrypt_file($processing); my $encrypted_output = "$dir/$processing"; #$dir is a global d +eclared at the top open OUT, "> $encrypted_output" || die "can't $!"; select OUT; print $file; rename("$dir/$file", "$dir/$file.pgp"); } } sub encrypt_file{ my $file = shift; my $pgp = Crypt::OpenPGP->new; my $ciphertext = $pgp-encrypt( Filename => $file, Recipient => $key_id, Armour => 1, ); return($ciphertext);

Replies are listed 'Best First'.
Re: How do I get the output of Crypt::OpenPGP to a file
by dga (Hermit) on Apr 04, 2003 at 16:11 UTC

    Instead of select I would just use the filehandle.

    open OUT, ... print OUT $file; close OUT; rename ...

    This will make sure the file data is flushed before the rename which isn't strictly necessary but makes things happen in the order you expect.

    Also, for readability, I would put a space between $processing and (@file).

Re: How do I get the output of Crypt::OpenPGP to a file
by hardburn (Abbot) on Apr 04, 2003 at 16:14 UTC

    You need to close your filehandle. My guess is that the data isn't being flushed from the buffer, and when you rename the file, it won't have the data written to it. Also, don't select filehanldes unless you really need to. Try:

    open OUT, "> $encrypted_output" or die "Can't open file: $!\n"; print OUT $file; close(OUT); rename("$dir/$file", "$dir/$file.pgp");

    And I don't see why you're renaming the file you just wrote instead of naming it that in the first place. Update: Last sentance was done with too much blood in my coffee stream.

    Repeat after me: I will always close my filehandles. I will always close my filehandles. I will always . . .

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

Re: How do I get the output of Crypt::OpenPGP to a file
by Aragorn (Curate) on Apr 04, 2003 at 16:15 UTC
    In the rename statement, you're renaming a file with filename of <encrypted data>, which is probably not what you want.

    I also don't understand what the rename is supposed to do. You can just open de output file with the right (.pgp) extension, print the encrypted data to it and be done with it.

    Arjen