CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [hwnd] Syntax Errors In Program With Hash: Edit Log



Kenosis
User

Mar 17, 2013, 2:50 PM


Views: 778
Re: [hwnd] Syntax Errors In Program With Hash

Using a filehandle variable allows you to pass it to or return it from a function, store in a structure, ...

A bareword file handle (reference) also allows these.

Passing a bareword file handle reference:


Code
use strict; 
use warnings;

readData( \*DATA );

sub readData {
my ($fh) = @_;

while (<$fh>) {
print;
}
}

__DATA__
This is some
Data that can be read
By passing a handle


Returning a bareword file handle reference:


Code
use warnings; 
use strict;

my $fh = getHandle();

while (<$fh>) {
print;
}

sub getHandle {
return \*DATA;
}

__DATA__
This is some
Data that can be read
By passing a handle


Storing a bareword file handle reference in a structure:


Code
use warnings; 
use strict;
use IO::File;

my %hash;

handleInHash(\%hash);

while (my $line = $hash{data}->getline) {
print $line;
}

sub handleInHash {
my ($hash_ref) = @_;
$$hash_ref{data} = \*DATA;
}

__DATA__
This is some
Data that can be read
By passing a handle


Output of all three:


Code
This is some 
Data that can be read
By passing a handle


The issue here is that bareword file handles are global, whereas lexically-scoped variables are not. For example:


Code
{ 
open FILE, '<', 'data.txt' or die $!;
}

my $line = <FILE>;
print $line;
close FILE;


works to read one line of the file data.txt--even though the bareword FILE was initialized within a code block--because FILE is global. However, the following:


Code
{ 
open my $FILE, '<', 'data.txt' or die $!;
}

my $line = <$FILE>;
print $line;
close $FILE;


doesn't work, because the value of $FILE is scoped within its code block, i.e., it's not global.

Using global variables can create some very problematic issues, so using my is encouraged...


(This post was edited by Kenosis on Mar 17, 2013, 3:22 PM)


Edit Log:
Post edited by Kenosis (User) on Mar 17, 2013, 3:10 PM
Post edited by Kenosis (User) on Mar 17, 2013, 3:11 PM
Post edited by Kenosis (User) on Mar 17, 2013, 3:15 PM
Post edited by Kenosis (User) on Mar 17, 2013, 3:16 PM
Post edited by Kenosis (User) on Mar 17, 2013, 3:17 PM
Post edited by Kenosis (User) on Mar 17, 2013, 3:22 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives