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

Hi all,
What is the most efficient way (performance-wise,memory-wise) to open a file and putting it into a scalar variable for printing? I'm returning it in a function call so it needs to be in a variable.

Replies are listed 'Best First'.
Re: Most efficient way to print a file?
by Anonyrnous Monk (Hermit) on Jan 03, 2011 at 13:11 UTC
    I'm returning it in a function call...

    In case the string is huge and you want to avoid some temporary memory allocation (which could push up the peak memory usage of the program), you could return a reference to the scalar:

    #!/usr/bin/perl sub mem { print "$_[0]:\n"; system "/bin/ps", "-osize,vsize", $$; } sub foo { mem(0); my $data; $data .= "xxxxxxxxxx" for 1..1_000_000; mem(1); return \$data; # return reference } my $r = foo(); # then get at the data using $$r mem(2); __END__ $ ./880173.pl 0: SZ VSZ 612 19804 1: SZ VSZ 10468 29660 2: SZ VSZ 10468 29660

    Using the same snippet, but with return $data, you'd get:

    0: SZ VSZ 612 19804 1: SZ VSZ 10468 29660 2: SZ VSZ 20236 39428

    As you can see, the process size has grown additionally by about the size of $data.

    Whether this really saves anything overall depends on what else the program is doing to actually print the string, etc.

      Ok, ill try that! But, what is the most efficient way to open the file?
        Really, does it matter? It's like asking the most efficient way to close your car door to minimize the time of your Miami to New York road trip.

        As the Anonymous Monk already said, you can use open or sysopen, but there probably won't be much difference, as most likely the majority of the time is spent in the underlying system call open(2), i.e. outside of the Perl program/in the kernel.

        If you really want to know: Benchmark.

Re: Most efficient way to print a file?
by dHarry (Abbot) on Jan 03, 2011 at 13:06 UTC

    I'm not sure if I understand you fully. You want to send a file to a printer and use Perl for that?

    I don't get why you want to put the data into a scalar in the first place? Why not send the file to the printer immediately? There several modules on CPAN to work with printers. Maybe Net::Printer? You didn't mention the platform you're on nor how your printing is setup. Maybe you should elaborate a bit.

    Cheers

    Harry

Re: Most efficient way to print a file?
by Anonymous Monk on Jan 03, 2011 at 12:01 UTC
    What is the most efficient way (performance-wise,memory-wise) to open a file and putting it into a scalar variable for printing?

    Seeing how there are only 2 pure-perl ways to do it, its either open/read, or sysopen/sysread -- sysopen might be faster (probably); I doubt it matters