
7stud
Enthusiast
Jan 14, 2013, 1:17 AM
Post #2 of 4
(438 views)
|
|
Re: [mar85] Problem Understanding Perl Syntax
[In reply to]
|
Can't Post
|
|
I don't understand what is -e, is it a switch perl has a feature called 'file tests', which look like command line switches. The -e file test returns true or false depending on whether the file with the given name *exists* or not. To test whether a file with the specified name exists and whether it is readable and writable, you can write this: To find out more about how file tests work, search google, or better yet buy the book "Learning Perl 6th edition". Note that using $_ in your code is frowned upon. Here is a better way:
for my $fname (@list_of_libs){ if(-e -r -w $fname) { } } You should also declare your variables with my() the first time you use them. And "for" can be used instead of "foreach", and it is shorter to type.
and what does -1 mean inside this line $list[-1]?
use strict; use warnings; use 5.012; my @data = ('a', 'b', 'c'); say $data[1]; say $data[-1]; --output:-- a c Using an index of -1 is a convenient way to get the last element of an array.
And also, what does die $! means? Is it to terminate the MAIN_LIB file? The standard way to open a file in perl is:
open INFILE, '<', "data.txt" or die "Couldn't open data.txt: $!"; If the file is successfully opened then open() returns a true value, and as a result what's to the right of an 'or' is skipped. If opening the file fails for some reason, then open returns undef, which is false, and that causes the right side of the 'or' to execute. The global variable $! contains the system error message that caused open() to fail. die() causes the program to terminate after printing out the specified string. By the way, you can look up the definition of any perl function on your computer like this: $ perldoc -f die Or, search google for "perl die" and look for a hit that is a "perldoc". perl has very good docs. Note that the code is using "bareword filehandles" and that is the old way of doing things. The new way looks like this:
open (my $infile, '<', "data.txt" or die "Couldn't open data.txt: $!"; I like to use all caps for variables containing filehandles, so I write that like this:
open (my $INFILE, '<', "data.txt" or die "Couldn't open data.txt: $!"; Most of the time it's not necessary, but it is considered good practice to close your file as soon as you are done with it: If you don't close your file, perl will automatically close the file when your program ends.
(This post was edited by 7stud on Jan 14, 2013, 1:50 AM)
|