[Israel.pm] convert perl string to file handle
Shlomi Fish
shlomif at iglu.org.il
Sun Jun 6 07:43:50 PDT 2004
On Sunday 06 June 2004 17:28, Offer Kaye wrote:
> > hi
> > is there a efficinet way to convert perl string to file handle?
> > i used something like:
> > $buffer="....."
> > open IN,qq{echo $buffer|};
> >
> > print <IN>;
> >
> > but is there a better way?
> > thank
> > itamar
>
> Hi Itamar,
> What exactly are you trying to do?
> Your above code just prints the string in $buffer to stdout. Did you
> perhaps mean to open the file whose name is in $buffer and print its
> contents? For that just do:
>
> my $buffer = "input_file_name";
> open(IN,$buffer) or die "Couldn't open $buffer for reading: $!\n";
> print <IN>;
> close(IN) or die "Couldn't close $buffer after reading: $!\n";
>
> of course you can also you the Unix "cat" command for this:
>
> my $buffer = "input_file_name";
> print `cat $buffer`;
>
A few notes regarding the above code. The first thing, is that after thinking
of it for a while I noticed you are doing something unnecessary here. You
output the file to the stdout, trap its contents, and then output it to
stdout again. This can be more easily achieved with:
<<<
my $buffer = "input_file_name";
system("cat", $buffer);
>>>
Nevertheless the `cat "$filename"` notation is useful and it is tempting to
use it to slurp a file. It is not recommended for the following reasons:
1. It is not portable outside UNIX. (and even on UNIX may potentially cause
problems.)
2. It is slower than the Perl implementation:
<<<
my $content;
{
open my $fh, "foo" or die #!;
local $/;
$content = <$fh>;
close $fh;
}
>>>
(there were others given in an entire article about slurp in Perl.com that was
presented recently, but this is the standard idiom).
3. It is prone to malicious input. If $filename is '"; rm -fr $HOME; echo "'
then what happens is left as an exercise to the reader.
4. Generally, calling the shell for help with what Perl can do by itself is
frowned upon for serious uses of Perl. While you are allowed to do it (after
all, TIMTOWDY), it is still bad style and unnecessary.
Best regards,
Shlomi Fish
> If this is not what you wanted to do please elaborate...
> ----------------------------------
> Offer Kaye
>
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://www.perl.org.il/mailman/listinfo/perl
--
---------------------------------------------------------------------
Shlomi Fish shlomif at iglu.org.il
Homepage: http://shlomif.il.eu.org/
Quidquid latine dictum sit, altum viditur.
[Whatever is said in Latin sounds profound.]
More information about the Perl
mailing list