Re: pointing a filehandle at a scalar or array ?
by davorg (Chancellor) on Jul 26, 2000 at 14:07 UTC
|
You could do something using tie. The docs for tie in 5.005_03 cover tieing filehandles but it's not mentioned in Perl In A Nutshell so I'm not sure when this support was added.
Update:
In fact there seems to be a Tie::Handle module that would serve as a base class for this. It's part of the standard distribution.
--
<http://www.dave.org.uk>
European Perl Conference - Sept 22/24 2000, ICA, London
<http://www.yapc.org/Europe/>
| [reply] [Watch: Dir/Any] |
|
#!/usr/bin/perl
my $damn_string = "This is so cool...\nThis is less cool.\nThis sucks.
+\n";
tie *H, 'str', $damn_string;
while(<H>) {
print "$_\n";
}
package str;
use Tie::Handle;
my @a;
sub TIEHANDLE {
my $i = bless \$i, shift;
@a = split "\n", shift;
return $i;
}
sub READLINE {
return shift @a;
}
| [reply] [Watch: Dir/Any] [d/l] |
RE: pointing a filehandle at a scalar or array ?
by merlyn (Sage) on Jul 26, 2000 at 16:47 UTC
|
| [reply] [Watch: Dir/Any] |
Re: pointing a filehandle at a scalar or array ?
by athomason (Curate) on Jul 26, 2000 at 14:18 UTC
|
If the data you want to pass is static (which I doubt, since there's little sense in using MIME::Decoder for static data), you could stick it at the end of your source after the __DATA__ line and just pass around the *DATA filehandle. A quick hack that is possibly more flexible would be to pass *STDOUT as the input for whatever function you're dealing with and then print to it. Actually, that sounds too funky, but it's late and I can nail down why (blocking issues?). As davorg mentioned above, your best bet is probably looking into using tie for dynamic data. | [reply] [Watch: Dir/Any] [d/l] [select] |
|
| [reply] [Watch: Dir/Any] [d/l] |
RE: pointing a filehandle at a scalar or array ?
by jimt (Chaplain) on Jul 26, 2000 at 20:05 UTC
|
This is interesting, since I've noticed a lot of people grumbling about this with modules that require globs (one of mine included). The true wizards can always overload a filehandle, using Tie::Handle if necessary.
But what I was wondering is if anyone thinks it'd be worthwhile for me (or someone else, I suppose) to whip up a module to wrap up all of this overloading stuff into one convenient package.
Say....Tie::UniversalHandle or something.
So you could just do:
tie *FH, Tie::UniversalHandle, $some_string;
or
tie *FH, Tie::UniversalHandle, @some_array;
and have all of the magic immediately wrapped up insde of the module. It'd spare people the trouble of having to roll their own module every time. | [reply] [Watch: Dir/Any] |
|
When faced with this sort of problem, I've found it useful
to just drop back one level of indirection and use subroutine
references:
my $gimme = $fh ? sub { <$fh> } : sub { pop @array };
...
while (defined($x = &$gimme)) {
...
}
| [reply] [Watch: Dir/Any] [d/l] |
A thnx to all of you
by lindex (Friar) on Jul 27, 2000 at 03:59 UTC
|
| [reply] [Watch: Dir/Any] [d/l] |