The handling of $_ is somewhat magical, and provided by the perl parser - not by the angle brackets. When perl sees this:
while (<>) {
}
It actually does this:
while (defined($_ = <ARGV>)) {
();
}
You can verify this yourself using
B::Deparse. Here is an example (assume test.pl as filename):
perl -MO=Deparse test.pl
Problems:
- By adding the test for $i <= 4 to the while loop you caused perl to skip the magical behaviour for while(<>).
- You should chomp the data that is being read in, otherwise instead of "1" you will have "1\n"
Suggestions:
- It is a better practice to use push instead of (@arr1,$_)
- use warnings instead of perl -w
New version of the code that addresses the above
#!/usr/bin/perl
use strict;
use warnings;
print "Enter 5 numbers: \n";
my $i=0;
my @arr1=();
while (<>) {
chomp;
push @arr1, $_;
last if ++$i > 4;
}
foreach my $m (@arr1) {
print $m, "\n";
}
Update
Additionally, please read
How To Ask A Question - Choose a Good, Descriptive Title
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.