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

I keep running into a problem when using perl CPAN modules.

Instead of taking scalars as data input, many modules only take filenames, and then read the file content as the input data.

For example the Mail::Sender has Attach method, but you have to specify a filename, which it then reads. You can't just specify the data as scalar you already have in memory.

What is a good way to get around this? Is there a way to make a file 'in memory' that perl modules can then 'read'?

Thanks.

Replies are listed 'Best First'.
Re: Using scalars as a file data?
by Loops (Curate) on Jul 31, 2013 at 00:01 UTC
    Yes, you can open a file handle for output or input against a string for instance:
    my $variable = "HELLO world\nhow are you?\n"; open(my $fh, '<', \$variable); print $_ for (<$fh>);
    Prints:
    HELLO world how are you?
    Although this wont work if the CPAN module only takes a filename, but usually modules that take a filename will also accept a file handle like the one created above.
Re: Using scalars as a file data?
by runrig (Abbot) on Jul 31, 2013 at 00:20 UTC

    While opening a reference to a scalar works for things that take a filehandle, there's not a lot you can do when something wants an actual filename, except to create a file and write the contents of the scalar to it.

    In the case of attachments for emails though, you might be better off using an alternative library, like MIME::Entity or MIME::Lite, which have more flexible attachment methods.

Re: Using scalars as a file data? (tempfile)
by Anonymous Monk on Jul 31, 2013 at 00:21 UTC