moderated >> reading from a file handle reference

by acrosby » Wed, 13 Oct 2004 02:31:35 GMT

I am trying to read from a file handle reference using the angle operator
<>. If I attempt to use a file handle that contains a hash reference I get
a syntax error similar to this:


$esfile = <{$drive_ref->{'reader'}}>; #points to a filehandle


Can't use subscript on glob at modules/UDO_general.pm line 267, near
"'reader'}"
syntax error at modules/UDO_general.pm line 267, near "}>"

But if I put the filehandle reference in a local variable, then I don't get
any error messages. I don't mind the intermediate step but I would like to
avoid it if possible. I can see that the interpreter gets confused the right
angle character in the hash reference, but I can't figure out how to escape
it.

Thanks in Advance,

Alan


moderated >> reading from a file handle reference

by Yitzchak Scott-Thoennes » Thu, 14 Oct 2004 02:07:12 GMT



<> has two different functions: one is reading a line from a file
(e.g. $line = <STDIN>; the other is expanding a shell filename
pattern (e.g. @files = <*.pl>).

If what's in the <> is a filehandle such as STDIN or a simple scalar
such as $fh, perl assumes you mean the former; otherwise it assumes
the latter.

You can make it do what you want by using readline() or glob() explicitly
instead of <>.

moderated >> reading from a file handle reference

by yf110 » Thu, 14 Oct 2004 02:47:10 GMT


: I am trying to read from a file handle reference using the angle operator
: <>. If I attempt to use a file handle that contains a hash reference I get
: a syntax error

perldoc perlop

look for I/O Operators, about twenty paragraphs down


"If angle brackets contain is a simple scalar variable (e.g.,
<$foo>), then that variable contains the name of the filehandle
..."


otherwise you get a glob, which in your case is synonymous with a mess.

moderated >> reading from a file handle reference

by Hans Mulder » Thu, 14 Oct 2004 03:12:30 GMT


Your problem is that the angle operator has two different meanings.
It can mean readline() or it can mean glob(). You want readline(),
but here you are getting the glob interpretation.

There are two things you can do. One is to spell readline in full:

$esfile = readline({$drive_ref->{'reader'}});

You've already found the other possibility:


I think most people do it this way; perhaps because it is suggested
in the description of the angle operator in perlop.

Hope this helps,

-- HansM

moderated >> reading from a file handle reference

by Gaal Yahas » Thu, 14 Oct 2004 03:59:43 GMT


[...]

Here are two other, stylistic reasons:

1. while (<>) gives you defined + assignment-to-$_ magic, readline()
doesn't;

2. If you're reading from this filehandle here, you'll likely also
do some more IO with it nearby, so having it ready in a short variable
may be handy.

--
Gaal Yahas < XXXX@XXXXX.COM >
http://gaal.livejournal.com/

moderated >> reading from a file handle reference

by acrosby » Fri, 15 Oct 2004 20:51:48 GMT

The contents of the variable was a filehandle. I probably should have
included more detail in my original post.

Here is my declaration in another portion of my code:

my %drive=( 'lib' => "",
'drv' => "",
'drive_type' => '',
'drive_sn' => "",
'output_filename' => "",
'raw_filename' => "",
'outfile_handle' => *OUT_FILE,
'rawfile_handle' => *RAW_FILE,

'reader' => *READER,
'writer' => *WRITER,

'fifo' => '',
'output_directory' => './seek_results/',
'raw_directory' => './seek_raw/',
'debug' => 0,
'errors' => 0,
'error_string' => '',
'testname' => 'UDO Seek',
'op_mode' => '',
'max_blocks' => 1831791,
'rep' => 1000,
);

What I ended up doing to fix the problem was copy the hash reference into a
local variable that did not have the reference notation (->).

$handle = $drive_ref->{'reader'};

$esfile = <$handle>;

I don't have any trouble using hash references with print, although I do
have to put braces around the hash reference. This is what made me believe
that there was some sort of
syntactic error that I wasn't aware of. Using the local variable is not a
problem; I just wanted to understand what I had done wrong.


print {$drive_ref->{'writer'}} "dpassthru 37000800000000000800
/bufsize=8\n";

It looks like using the readline function directly may be the way to go, but
I haven't had a chance to try it yet.

moderated >> reading from a file handle reference

by Yitzchak Scott-Thoennes » Sat, 16 Oct 2004 01:35:04 GMT


Not true; readline is the same as <>:

$ perl -MO=Deparse -e'while (readline <STDIN>) { }'
while (defined($_ = readline <STDIN>)) {
();
}

moderated >> reading from a file handle reference

by Gaal Yahas » Sat, 16 Oct 2004 13:01:20 GMT


I stand corrected! Note, though, that you probably wanted "*STDIN"
rather than "<STDIN>" in the example above.

perl -MO=Deparse -e'while (readline *STDIN) { }'
while (defined($_ = <STDIN>)) {
();
}

--
Gaal Yahas < XXXX@XXXXX.COM >
http://gaal.livejournal.com/

moderated >> reading from a file handle reference

by Yitzchak Scott-Thoennes » Mon, 18 Oct 2004 17:48:37 GMT


I certainly did! :)

moderated >> reading from a file handle reference

by Yitzchak Scott-Thoennes » Tue, 14 Dec 2004 11:53:17 GMT

would pursue their own
advantage at the expense of the system.

52. Suppose that a public official or a corporation executive appoints
his cousin, his friend or his co-religionist to a position rather than
appointing the person best qualified for the job. He has permitted
personal loyalty to supersede his loyalty to the system, and that is
"nepotism" or "discrimination," both of which are terrible sins in
modern society. Would-be industrial societies that have done a poor
job of subordinating personal or local loyalties to loyalty to the
system are usually very inefficient. (Look at Latin America.) Thus an
advanced industrial society can tolerate only those small-scale
communities that are emasculated, tamed and made into tools of the
system. [7]

53. Crowding, rapid change and the breakdown of communities have been
widely recognized as sources of social problems. but we do not believe
they are enough to account for the extent of the problems that are
seen today.

54. A few pre-industrial cities were very large and crowded, yet their
inhabitants do not seem to have suffered from psychological problems
to the same extent as modern man. In America today there still are
uncrowded rural areas, and we find there the same problems as in urban
areas, though the problems tend to be less acute in the rural areas.
Thus crowding does not seem to be the decisive factor.

55. On the growing edge of the American frontier during the 19th
century, the mo

moderated >> reading from a file handle reference

by acrosby » Tue, 14 Dec 2004 14:19:00 GMT

wee can envision no plausible scenarios that
are any more palatable that the ones we've just described. It is
overwhelmingly probable that if the industrial-technological system
survives the next 40 to 100 years, it will by that time have developed
certain general characteristics: Individuals (at least those of the
"bourgeois" type, who are integrated into the system and make it run,
and who therefore have all the power) will be more dependent than ever
on large organizations; they will be more "socialized" that ever and
their physical and mental qualities to a significant extent (possibly
to a very great extent ) will be those that are engineered into them
rather than being the results of chance (or of God's will, or
whatever); and whatever may be left of wild nature will be reduced to
remnants preserved for scientific study and kept under the supervision
and management of scientists (hence it will no longer be truly wild).
In the long run (say a few centuries from now) it is it is likely that
neither the human race nor any other important organisms will exist as
we know them today, because once you start modifying organisms through
genetic engineering there is no reason to stop at any particular
point, so that the modifications will probably continue until man and
other organisms have been utterly transformed.

178. Whatever else may be the cas

moderated >> reading from a file handle reference

by Hans Mulder » Tue, 14 Dec 2004 14:31:14 GMT

that turning them off would
amount to suicide.

174. On the other hand it is possible that human control over the
machines may be retained. In that case the average man may have
control over certain private machines of his own, such as his car of
his personal computer, but control over large systems of machines will
be in the hands of a tiny elite -- just as it is today, but with two
difference. Due to improved techniques the elite will have greater
control over the masses; and because human work will no longer be
necessary the masses will be superfluous, a useless burden on the
system. If the elite is ruthless the may simply decide to exterminate
the mass of humanity. If they are humane they may use propaganda or
other psychological or biological techniques to reduce the birth rate
until the mass of humanity becomes extinct, leaving the world to the
elite. Or, if the elite consist of soft-hearted liberals, they may
decide to play the role of good shepherds to the rest of the human
race. They will see to it that everyone's physical needs are
satisfied, that all children are raised under psychologically hygienic
conditions, that everyone has a wholesome hobby to keep him busy, and
that anyone who may become dissatisfied undergoes "treatment" to cure
his "problem." Of course, life will be so purposeless that people will
have to be biologically or psychologically engineered either to remove

moderated >> reading from a file handle reference

by Yitzchak Scott-Thoennes » Tue, 14 Dec 2004 14:54:45 GMT

closer ties to Britain, and would have had
a Parliament and Prime Minister instead of a Congress and President.
No big deal. Thus the American Revolution provides not a
counterexample to our principles but a good illustration of them.

110. Still, one has to use common sense in applying the principles.
They are expressed in imprecise language that allows latitude for
interpretation, and exceptions to them can be found. So we present
these principles not as inviolable laws but as rules of thumb, or
guides to thinking, that may provide a partial antidote to naive ideas
about the future of society. The principles should be borne constantly
in mind, and whenever one reaches a conclusion that conflicts with
them one should carefully reexamine one's thinking and retain the
conclusion only if one has good, solid reasons for doing so.

INDUSTRIAL-TECHNOLOGICAL SOCIETY CANNOT BE REFORMED



111. The foregoing principles help to show how hopelessly difficult it
would be to reform the industrial system in such a way as to prevent
it from progressively narrowing our sphere of freedom. There has been
a consistent tendency, going back at least

moderated >> reading from a file handle reference

by Gaal Yahas » Tue, 14 Dec 2004 14:56:37 GMT

and dignity. Still, the technology would remain waiting.
Sooner or later the social arrangement would break down. Probably
sooner, given that pace of change in our society. Then genetic
engineering would begin to invade our sphere of freedom, and this
invasion would be irreversible (short of a breakdown of technological
civilization itself). Any illusions about achieving anything permanent
through social arrangements should be dispelled by what is currently
happening with environmental legislation. A few years ago it seemed
that there were secure legal barriers preventing at least SOME of the
worst forms of environmental degradation. A change in the political
wind, and those barriers begin to crumble.

134. For all of the foregoing reasons, technology is a more powerful
social force than the aspiration for freedom. But this statement
requires an important qualification. It appears that during the next
several decades the industrial-technological system will be undergoing
severe stresses due to economic and environmental problems, and
especially due to problems of human behavior (alienation, rebellion,
hostility, a variety of social and psychological difficulties). We
hope that the stresses through which the system is likely to pass will
cause it to break down, or at least weaken it sufficiently so that a
revolution occurs and is successful, then at that particular moment
the aspiration for freedom will have proved more powerful than
technology.

135. In paragraph 125 we used an

moderated >> reading from a file handle reference

by Gaal Yahas » Tue, 14 Dec 2004 15:16:58 GMT

they
can do legally (or sometimes illegally) to restrict or circumvent
those rights. Most of these educators, government officials and law
officers believe in freedom, privacy and constitutional rights, but
when these conflict with their work, they usually feel that their work
is more important.

132. It is well known that people generally work better and more
persistently when striving for a reward than when attempting to avoid
a punishment or negative outcome. Scientists and other technicians are
motivated mainly by the rewards they get through their work. But those
who oppose technilogiccal invasions of freedom are working to avoid a
negative outcome, consequently there are a few who work persistently
and well at this discouraging task. If reformers ever achieved a
signal victory that seemed to set up a solid barrier against further
erosion of freedom through technological progress, most would tend to
relax and turn their attention to more agreeable pursuits. But the
scientists would remain busy in their laboratories, and technology as
it progresses would find ways, in spite of any barriers, to exert more
and more control over individuals and make them always more dependent
on the system.

133. No social arrangements, whether laws, institutions, customs or
ethical codes, can provide permanent protection against technology.
History shows that all social arrangements are transitory; they all
change or break down eventually. But technological advances are
permanent within the context of a given civilization. Suppose

Similar Threads

1. File Handle Reading Blues: Rereading a File Handle for Input

Hi.
I can't reread a file handle after I have copied it on another file
handle for output.  Here is the code snippet.  Please let me know if
you need more.
Lines 26 & 27 are my attempts to get read the input file again.  Line
18, where I copy the input file handle to the output file handle works
fine.  I am using Perl 5.6.1 on HP-UX 11.00.

    18     print INVARS_NW <INVARS_READ>;
    19
    20     chomp ($DB_MAIN_NAME=`echo \$profile`);
    21     #system "echo \$profile";
    22     print "DB_MAIN_NAME = '$DB_MAIN_NAME'";
    23
    24     print "\nGeorge W.";
    25
    26     while (<INVARS_READ>)
    27     #while (print INVARS_NW <INVARS_READ>)
    28     {

Thank you.

2. [ANN] reference 0.5 (was object reference handle (like perl's reference to scalar))

3. Introducing Features of other Languages (was: object reference handle (like perl's reference to scalar))

"Dave Burt" < XXXX@XXXXX.COM > schrieb im Newsbeitrag 
news:gobfe.6148$ XXXX@XXXXX.COM ...
>
> "Robert Klemme" < XXXX@XXXXX.COM > wrote:
>>>> <soapbox>
>>>> It still might be worthwile, I just get the feeling that people try to 
>>>> stuff things from other programming languages into Ruby because they 
>>>> found them cute / useful / the only way to solve certain things in that 
>>>> language.  IMHO programming languages are different for a reason and 
>>>> often it's much better to adhere to the old saying "when in Rome do as 
>>>> the Romans do"... :-)
>>>> </soapbox>
>
>> "Dave Burt" < XXXX@XXXXX.COM > schrieb:
>>> I don't think what I've done here is anything like that.
>
>> I had to place that comment in some of these threads that I feel we're 
>> seing more and more recently.  I probably didn't pick the most 
>> appropriate one... :-)
>
> There are two reasons I like these threads.
>
> The first is that when Perl- or C- or Whatever-thinkers ask these 
> questions to this list, they will be exposed to the Ruby Way of solving a 
> class of problems, and helped to free their mind.

I heartily agree here.  But of course this needs some form of openness on 
both sides, careful listening and considering arguments.  Pure evangelism 
doesn't help.

> Secondly, Ruby's a great language to push around and mould to your own 
> whim as a programmer. It's a great language to create DSLs in. These 
> interesting hacks are not going to displace the Ruby Way, but they help 
> expand my thinking in a similar way to learning Ruby (where I learned to 
> routinely use closures and meta-programming).

Yes, of course.  However there's a difference between building a DSL and 
modifying fundamental behavior of the language.  The second approach is the 
one that arouses my suspicion.

>>> ... all I'm proposing is a new container, for a single object.
>>>
>>> And I think Austin's PDF::Writer example is one case where it's useful 
>>> (that is, passing an object by reference into a method so the method can 
>>> replace the object).
>>
>> Yuck, may well be.  On a side note, the fact that ruby methods can return 
>> an arbitrary number of objects is a really great thing, that can also 
>> help with some of these replacement problems.
>
> Heh, I think that's Austin's view, too. He seems to badly want to rewrite 
> it :) Anyway, multiple returns are interesting. You get an extra container 
> there, too (My Ref is just an extra container). They're often quite 
> disobvious, and I'm sure there are cases where it would seem more obvious 
> to modify an argument "in-place", even though "that's not possible in 
> Ruby".

Personally I prefer to not have in place modification.  If you view a method 
as some kind of (mathematical) function, then there's an input and an 
output.  Returning values via arguments (= input) feels a bit awkward to me. 
It has to be done in other languages because they don't provide multiple 
return values; unfortunately this can make code hard to read.  But since 
Ruby actually has mutliple returns, I personally prefer to do it that way.

Kind regards

    robert

4. object reference handle (like perl's reference to scalar)

5. File handling with subroutines and references

I am processing multiple files and am trying to create routines that
will efficiently read/write files. I am using variable names for the
FILEHANDLE to prevent any conflicts during processing (Is this a good
practice or is there a *better* way?).

use strict; use warnings;
no strict 'refs';
use Fcntl qw(:DEFAULT :flock);

sub file_open {
    my ($fh, $file, $mode) = @_;
    open($fh, "$mode $file") || die("Cannot open $file: $!");
    flock($fh, LOCK_EX);
    return \*$fh;
}

sub file_close {
  my $fh = shift;
  close($fh);
}

my $file = "data.txt";
my $fh = file_open("TEST_OUT", $file, '+<');
my $out = file_open("TEST_IN", "data_out.txt", '+>');
while (<$fh>) {
    # process data
    # ...
    print $out $_;
}
file_close($out);
file_close($fh);

__END__

I tried:
sub file_open {
    my ($fh, $file, $mode) = @_;
    my $filehandle = do { local *$fh }; # <-- ADDED
    open($filehandle, "$mode $file") || die("Cannot open $file: $!");
    flock($filehandle, LOCK_EX);
    return \*$filehandle;
}

which I saw in an example. I've seen it used for file "slurping", but I
am not sure if it is something I should use. My understanding is that
it is used to make the FILEHANDLE local, but in the context that I am
using, it doesn't seem necessary.

I know there are modules out there to use, but I am not using them
because I need the code to work with the standard 5.004 Perl install.

I'm looking for any code/design comments. Anything that I'm not doing
or that I should be doing?

Thanks,
Eric

6. reading from scalar File::Temp handle - Perl

7. Read quicker than a line per time from a file handle

Hi 
         I try to measure how fast an ftp download is going on the
fly. I do something like:

$|=1; 
my $count =0;
open (CMD, "ftp.script 2>&1 |") or die "Can't execute: $!";
while (<CMD>){
	print "Result: $_ \n";	
	if ($_ =~ /\#/) {
		$count ++;
	
}

The problem is that the 'ftp.script' returns me the hashes, but all
toghter. So basically $count is only 1 after execution. In other words
the output that I get is:
Result: Connected to... bla bla
Result: Downloading ...
Result: ######################################################
Result: Download complete

What I want is:
Result: Connected to... bla bla
Result: Downloading ...
Result: #
Result: #
Result: #
Result: #
Result: #
Result: #
Result: #
  ....
Result: Download complete


I have tried $|=1; but it does not help. The original script does
write the hashes one by one to STDOUT. Is there any way to force
'ftp.script' to pass me the hashes one by one? I use a windows
machine.

Thanks
        Carlo

8. Assigning one file handle to another file handle... - Perl