Académique Documents
Professionnel Documents
Culture Documents
PERL
AGENDA
References
File Operators
Reading From a File Writing into File
Page 1
1
REFERENCES
Page 2
References - Preface
Need for more complex data structures, than simple variables
and lists
Perls 3 built-in types combine with references, gives arbitrarily complex and powerful data structures A selection between an elegant program doing its job quickly and a program that consumes system resources voraciously
Page 3
What is a Reference?
A reference is a scalar value that points to a memory location of another variable in memory.
Reference 0x305108
Referent 0x351f00 5
$a
$b
Page 4
Creating a Reference
A reference of a variable can be got when a backslash is put in front of it.
$a = \$b; 0x305108 0x351f00 5
$a
SCALAR (0X351f00)
$b
Page 5
location
$$a = 3;
0x305108
0x351f00 3
$a
SCALAR (0X351f00)
$b
Page 6
Page 7
Accessing References
In order to access a reference, you have to tell Perl to access the information at the address instead of the address itself. An extra dollar sign ($) can be used for that.
Page 8
References
$refArray = \@array;
$refHash = \%hash;
$refFunction = \&function;
Page 9
2
File Handle
Page 10
-e
-f -M
-r
-s -w -x -z
Page 11
to check if it is readable
returns the size of the file to check if it is writable to check if it is executable to check if the size is zero
Example
$file=C:\\file1.txt; if (-e $file) { $size= -s $file; print $size , " bytes \n"; if (-z $file) { print" There is no data in $file \n"; } }
Page 12
FILE Handling
A file is opened using open function
To read
open(FILE_HANDLE, file-path\\filename) or warn Can not open filename: $!;
To create\overwrite
open(FILE_HANDLE, >file-path\\filename) or die Can not create filename: $!;
To append
open(FILE_HANDLE, >>$filename) or die Can not append $filename: $!;
Page 13
Open a file
Syntax
open(<Filehandle>, <path>/<filename>);
Example
open(INFO, ">$file");
Page 14
open FILE,"C:\\file1.txt" or die "oops: $!"; seek FILE,10,0; @line = <FILE>; print @line; close(FILE);
Page 16
open FILE,>C:\\file1.txt" or die "oops: $!"; print FILE Hello world; close (FILE);
Page 17
Page 18
Close file
Syntax
Close (<Filehandle>)
Example
Page 19
Imagination
Page 20
Action
Joy