On Dec 28, 2007 6:42 AM, <[EMAIL PROTECTED]> wrote:
> Hi all,
> I am new user of this group. can you tell how can i accept
> array elements using loop. for example
> for($i=0;$i<5;$i++)
> {
> $a[$i]=<stdin>;
> }
While this does appear to be valid syntax (except that it is STDIN not
stdin), it is more Perlish to say
for (1 .. 5) {
push @a, scalar <STDIN>;
}
or better yet, since STDIN is the file* that is read from when you
used just use <>
for (1 .. 5) {
push @a, scalar <>;
}
and while we are at it we can use the conditional form of the for loop
push @a, scalar <> for 1 .. 5;
We could also say
my @a = map { scalar <> } 1 .. 5;
if we wanted to initialize @a when we declare it.
Of course, all of this is moot if @a already has data in it and you
want to replace the first five items. In that case you should use
splice:
splice @a, 0, 5, map { scalar <> } 1 .. 5;
* <> has a little bit of magic to it, it will read from STDIN if there
is nothing in @ARGV, but if there are items in @ARGV it will try to
open and read from them instead. This is often the behavior you
desire (see grep, tr, or any of the other filtering UNIX commands).
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/