Home > Archive > PERL Beginners > December 2007 > how to accept array elments using loop
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
how to accept array elments using loop
|
|
| lumadhu@gmail.com 2007-12-28, 8:00 am |
| 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>;
}
| |
| Jeff Pang 2007-12-28, 8:00 am |
| On Dec 28, 2007 7:42 PM, <lumadhu@gmail.com> 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>;
> }
>
use strict;
my @arr;
while(<> ) {
chomp;
push @arr,$_;
}
| |
| Paul Lalli 2007-12-28, 7:01 pm |
| On Dec 28, 6:42=A0am, luma...@gmail.com wrote:
> =A0 =A0 =A0 =A0 =A0 =A0I am new user of this group. can you tell how can i=
accept
> array elements using loop. for example
> for($i=3D0;$i<5;$i++)
> {
> =A0 $a[$i]=3D<stdin>;
> }
What, exactly, is wrong with the solution you provided right there?
How does it not meet your needs? What do you want to do instead of
that?
Paul Lalli
| |
| John W. Krahn 2007-12-28, 7:01 pm |
| lumadhu@gmail.com wrote:
> Hi all,
Hello,
> 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>;
> }
my @a = map scalar <STDIN>, 1 .. 5;
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
| |
| Chas. Owens 2007-12-28, 7:01 pm |
| On Dec 28, 2007 6:42 AM, <lumadhu@gmail.com> 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).
|
|
|
|
|