CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Initializing an array with a specific value

 



chanwkcom
New User

Dec 4, 2010, 5:35 PM

Post #1 of 4 (317 views)
Initializing an array with a specific value Can't Post

Hello,

I'm a novice at Perl Programming. I have a quick question.

I'd like to make an array of size 1000, and I want each element to be initialized to one.

A simple approach that I can think of is just using the for-loop.

@array = ();

for (my $i = 0; $i < 1000; $i++)

{

$array[$i] = 1;
}



However, the above code does not look elegant. Could anyone tell me what would be an efficient way of doing this?

Thank you in advance!


shawnhcorey
Enthusiast


Dec 4, 2010, 5:39 PM

Post #2 of 4 (315 views)
Re: [chanwkcom] Initializing an array with a specific value [In reply to] Can't Post

Always put these use statements at the top of every script:

Code
use strict; 
use warnings;


Use the x operator to get multiple values:

Code
my @array = ( 1 ) x 1_000;


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


chanwkcom
New User

Dec 4, 2010, 5:54 PM

Post #3 of 4 (313 views)
Re: [shawnhcorey] Initializing an array with a specific value [In reply to] Can't Post

Thank you very much!Smile


perlJunkie
Novice

Dec 26, 2010, 11:33 PM

Post #4 of 4 (286 views)
Re: [chanwkcom] Initializing an array with a specific value [In reply to] Can't Post

You can also try:

my @array;
foreach (1..1000) { $arrary[$_] = 1; }

I think its clear and simple..........

Peace

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives