Re: the FOR Loop in the English Language
- From: usenet@xxxxxxxxxxxxxxx
- Date: 29 Jun 2006 15:56:35 -0700
jm-1@xxxxxxxxxxxxxxxxx wrote:
@one_to_ten = (1 .. 10);
$top_limit = 25;
for $i (@one_to_ten, 15, 20 .. $top_limit) {
print "$i\n";
}
You would have less to explain if you didn't bother with the constraint
variables (maybe having $top_limit is OK, but @one_to_ten is silly).
And it would be more clear if you named your loop variable something
more sensible. Consider:
foreach my $number ( (1..10), 15, 20, (20..25) ) {
print "$number\n";
}
Of course, you don't need parens around (1..10) but I think it improves
readability.
Can somebody explain this same code whilst reading a text file into an
array? What is the syntax to read a file called "shopping-list.txt"
into an array and print each item out to the screen?
It's almost always unnecessary (and unwise) to read a file into an
array (if you try this with a very large file, you can easily run out
of memory). This is a common mistake in programming logic, especially
for new programmers. A file is usually processed one record at a time,
so just read one record at a time and process each record as it is
read. For example:
open($shopping_list, 'shopping-list.txt') or die "Oops - $!\n";
while ( my $item = <$shopping_list> ) {
print "$item\n";
}
For such a trivial loop, though, many programmers would simply do:
print while <$shopping_list>;
But if you insist on using the array,
my @unnecessary_array = <$shopping_list>; #bad idea
How does perl decide what characters or words or lines will be assigned
to what element of the array? A line at a time? A word at a time? A
letter at a time etc..
Any of the above are possible. It depends on what you have defined as
a record separator. By default, the record separator is a newline
(whatever a newline is in your operating system), so it reads one line
at a time. You can set your record separator to whatever you like (if
you make it a space, Perl will read one word at a time). The value for
the record separator is contained in the Perl special variable $/. If
that name is too cryptic, you can "use English;" and then refer to it
by either $INPUT_RECORD_SEPARATOR or $RS.
I would love to see a website that explained things in this way!
Then you may appreciate Elizabeth Castro's 'Visual Quickstart' books.
You will outgrow them quickly, though.
--
David Filmer (http://DavidFilmer.com)
.
- References:
- the FOR Loop in the English Language
- From: jm-1
- the FOR Loop in the English Language
- Prev by Date: Re: Script Required to Check a range of IP's
- Next by Date: Detecting line terminators in a CSV file
- Previous by thread: the FOR Loop in the English Language
- Next by thread: Re: the FOR Loop in the English Language
- Index(es):
Relevant Pages
|