Welcome to Dream.In.Code
Getting Help is Easy!

Join 132,694 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,314 people online right now. Registration is fast and FREE... Join Now!




Help with arrays in Perl

 
Reply to this topicStart new topic

Help with arrays in Perl

enigma-paradox
post 16 Jun, 2008 - 03:00 PM
Post #1


New D.I.C Head

*
Joined: 16 Jun, 2008
Posts: 8

I'm a really new programmer and I'm trying to teach myself Perl.

I know that in Java if you want to create an array to hold 10 items you would use the following
int[] a = new int[10];

but I don't know how to do the same thing in Perl. I'm pretty sure that @a=<>; would be what I need to use. The part that I'm not sure about is how to let it know that I only want 10 items. When I try typing something like this, I get an error message.

Can some body help me?
User is offlineProfile CardPM

Go to the top of the page

girasquid
post 16 Jun, 2008 - 03:05 PM
Post #2


Barbarbar

Group Icon
Joined: 3 Oct, 2006
Posts: 1,256



Thanked 14 times

Dream Kudos: 650
My Contributions


Something like this is what you want:
CODE

#!/usr/bin/perl -w
use strict;
my @array = ();

And because Perl is loosely-typed, that array will hold any number of items - from 1 to 100 and beyond.
User is offlineProfile CardPM

Go to the top of the page

KevinADC
post 16 Jun, 2008 - 04:33 PM
Post #3


D.I.C Head

Group Icon
Joined: 23 Jan, 2007
Posts: 213



Thanked 3 times

Dream Kudos: 50
My Contributions


QUOTE(enigma-paradox @ 16 Jun, 2008 - 04:00 PM) *

I'm a really new programmer and I'm trying to teach myself Perl.

I know that in Java if you want to create an array to hold 10 items you would use the following
int[] a = new int[10];

but I don't know how to do the same thing in Perl. I'm pretty sure that @a=<>; would be what I need to use. The part that I'm not sure about is how to let it know that I only want 10 items. When I try typing something like this, I get an error message.

Can some body help me?


With perl it is almost never necessary to allocate buckets. You can just add stuff to an array when you initialize it or later as needed. If you never want the array to go past ten elements you need to specifically check the length of the array and adjust it as needed:

CODE
if (scalar @array > 10) {
   # array is too long, pop it or shift it or whatever
}


You don't need to use the 'scalar' keyword in the above code, I only use it for clarification.
User is offlineProfile CardPM

Go to the top of the page

enigma-paradox
post 17 Jun, 2008 - 01:30 PM
Post #4


New D.I.C Head

*
Joined: 16 Jun, 2008
Posts: 8

I'm still not sure how you would do that. Below is a simple program that I wrote for class in java and I know that it works. I'm trying to write the same program in perl and I can't seem to get it to work.

Java code

import java.util.Scanner;
import java.text.NumberFormat;

public class quiz
{
public static void main(String[] args)
{

int questions;
Scanner scan = new Scanner(System.in);

System.out.println("How many questions are on the quiz?");
questions = scan.nextInt();

int[] key = new int[questions];

for (int i=0; i< questions; i++)
{

System.out.println("Please enter the answer key");
key [i] = scan.nextInt();

}


int [] answers = new int[questions];

for (int i=0; i< questions; i++)
{
System.out.println("Please enter the student's answers");
answers [i] = scan.nextInt();
}


double percent;
String response;

NumberFormat fmt1 = NumberFormat.getPercentInstance();
do
{


int correct = 0;

for (int i = 0; i < answers.length; i++)
if ( key[i] == answers[i])
{

correct +=1;
}

percent= (double) correct/questions;
System.out.println ("The student got" + correct + "answers correct");
System.out.println ("The student scored" + fmt1.format(percent)+ "on this quiz");
System.out.println ("Would you like to score another quiz? (y/n)");
response = scan.next();
}
while (response.equals( "y"));
}
}

Perl Code
#!/usr/bin/perl
print("How many questions are on the quiz?\n");
$questions = <>;
@key=();
$questions = @key;
for($i=0; $i<$questions;$i++)
{
print("Please enter the answer key");
pop(@key)=<>;
}
@answers=();
$questions= @answers;
for($i=0; $i<$questions, $i++)
{
print("Please enter the student's answers");
pop(@key)=<>;
}
do
{
$correct=0;
for($i=0;$i<$questions;$i++)
if (@key[$i] == @answers[$i])
{
$correct += 1;
}
print("The student got" + $correct+ "answers correct\n");

}
User is offlineProfile CardPM

Go to the top of the page

KevinADC
post 17 Jun, 2008 - 02:02 PM
Post #5


D.I.C Head

Group Icon
Joined: 23 Jan, 2007
Posts: 213



Thanked 3 times

Dream Kudos: 50
My Contributions


'pop' removes the last element of an array, I think you want to use 'push' to append new elements to the end of the array. THere are other issues with your code, but I don't have the time right now to expalin them all, here is the code written to at least work, I think, I don't have time to test it:

CODE
#!/usr/bin/perl

#all perl scripts should use these two pragmas:
use strict;
use warnings;

print "How many questions are on the quiz?\n";
chomp (my $questions = <STDIN>);#<-- you should chomp the input
my @key = ();
my @answers = ();

for (1 .. $questions){ #<-- note perl style loops
   print "\nPlease enter the answer key:";
   chomp(my $q = <STDIN>);
   push @key, $q;;
}

for (1 .. $questions){
   print "\nPlease enter the student's answers:";
   chomp (my $r = <STDIN>);
   push @answers, $r;
}

do {
   my $correct = 0;
   for my $i (0 .. $questions-1){
      # uncomment next line for debugging
      # print ">> $key[$i] == $answers[$i]\n";
      if ($key[$i] == $answers[$i]){
         $correct++;
      }
   }
   print "The student got  $correct answers correct\n";
}


Note: "==" checks numbers, not strings. Ask questions and I will try and answer them later.
User is offlineProfile CardPM

Go to the top of the page

enigma-paradox
post 17 Jun, 2008 - 05:15 PM
Post #6


New D.I.C Head

*
Joined: 16 Jun, 2008
Posts: 8

there are a few questions that I have. Like I said I'm trying to teach my self perl.
1. I what is the diffeence between
@key= (); and my @key=(); ?

2. I know how a regular for loop works, but why is a for loop different in perl and what do the differences mean?

3. What does STDIN mean?

4.Where did $q and $r come from? I can't really tell what these varialbes are doing.

push @answers, $r; is what I wanted to know originally. This is what you used so that you only enter a specified number of elements in your code right? That was my original question.

5. Also what's wrong with my perl code exactly? I know that it works in java.

also, are there any books or websites that anyone would recomend for learning perl?
User is offlineProfile CardPM

Go to the top of the page

KevinADC
post 17 Jun, 2008 - 07:22 PM
Post #7


D.I.C Head

Group Icon
Joined: 23 Jan, 2007
Posts: 213



Thanked 3 times

Dream Kudos: 50
My Contributions


QUOTE(enigma-paradox @ 17 Jun, 2008 - 06:15 PM) *

there are a few questions that I have. Like I said I'm trying to teach my self perl.
1. I what is the diffeence between
@key= (); and my @key=(); ?

2. I know how a regular for loop works, but why is a for loop different in perl and what do the differences mean?

3. What does STDIN mean?

4.Where did $q and $r come from? I can't really tell what these varialbes are doing.

push @answers, $r; is what I wanted to know originally. This is what you used so that you only enter a specified number of elements in your code right? That was my original question.

5. Also what's wrong with my perl code exactly? I know that it works in java.

also, are there any books or websites that anyone would recomend for learning perl?


1. My code uses the "strict" pragma, which forces you to declare almost all of your variables with the keyword "my". Nearly all perl scripts should use "strict", and it is especially important for beginners as it catches many errors that are hard to spot otherwise.


2. You were using C style loops: for($i=0; $i<$questions;$i++)

In perl you can use a range to create a loop of n numbers: for (1 .. $questions)

There is nothing "wrong" with C style loops. The two style of loops work the same although the way I coded the loop is probably more efficient.

3. STDIN is user input from the console and other sources of input into a perl program. Its basically a filehandle.

4. $q and $r are just variables to store the value of the user intput. They can be named anything.

5. The obvious answer is that your code does not work, probably just because of using "pop" instead of "push" but the coding style is also old. I'm not sure what your learning material is but if it shows to use this syntax: @key[$i] it is very old. Perl 5.xx still supports that old style syntax to access the elements of arrays but it will generate a warning (if warnings are turned on and they should be).

You should also not wrap print commands in parenthesis:

CODE

print ("blah blah");


should be:

CODE
print "blah blah";


or really if there are no variables or meta characters:

CODE
print 'blah blah';


See here for more details: http://perldoc.perl.org/functions/print.html

The do {} block at the end of the code is not really needed but it does no harm to have it in.

A good place to start with perl is the "tutorial" section of the perlmonks website: http://www.perlmonks.com/index.pl?node=Tutorials

Also http://perldoc.perl.org/
User is offlineProfile CardPM

Go to the top of the page

KevinADC
post 17 Jun, 2008 - 11:32 PM
Post #8


D.I.C Head

Group Icon
Joined: 23 Jan, 2007
Posts: 213



Thanked 3 times

Dream Kudos: 50
My Contributions


I should also say, your code is by no means bad. For a self learning beginner your code is pretty good. I can't say or recommend it enough though, use strict and warnings:

use strict;
use warnings;
use diagnostics;

"diagnostics" is optional but might be good for now. You can look them up under the "pragmas" section of the perl documentation.

http://perldoc.perl.org/index-pragmas.html
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 11/23/08 07:46AM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month