Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

New student, can we write this program in perl...

by rahulraina7 (Initiate)
on Oct 19, 2012 at 16:32 UTC ( #999976=perlquestion: print w/replies, xml ) Need Help??
rahulraina7 has asked for the wisdom of the Perl Monks concerning the following question:

Can we write a program in perl which accepts an array of numbers and separates the even and odd numbers in the array into two different arrays. If possible please somebody give me the code, i know it is very small and i know the c/c++ code this , but as i am a completely new guy and u can say dummy in perl please help me.

  • Comment on New student, can we write this program in perl...

Replies are listed 'Best First'.
Re: New student, can we write this program in perl...
by MidLifeXis (Monsignor) on Oct 19, 2012 at 16:49 UTC

    I would use grep and the % operator. Could also do it with the ternary operator and the % operator (although that is approaching too cute to maintain).

    Update: based on other provided information in this thread, you may also want to see print, join, say, and chomp.


      how do i input array of n numbers in perl sir ..?

        my @data = <> would be one way. Could always read one line at a time with while (<>) {...}. This is stuff that you or your instructor should have already covered in your course, isn't it?

        Update: if not, take a look at perlintro, perlfaq, perlsyn, perldata, and so on.


Re: New student, can we write this program in perl...
by choroba (Chancellor) on Oct 19, 2012 at 16:36 UTC
    Hallo rahulraina7, wellcome to the Monastery.

    This is not a code writing service. Can you show how you would solve the problem in C? We can then describe what changes you should do to the code to translate it to Perl.

    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Thank you Choroba Sir for your interest , please have a look at C code.

      #include<stdio.h> #include<conio.h> void main() { int a[20],b[20],c[20],i,j=0,k=0,n; clrscr(); printf("Enter the number of elements"); scanf("%d",&n); printf("Enter n numbers\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { if((a[i]%2)==0) { b[j]=a[i]; j++; } else { c[k]=a[i]; k++; } } printf("The even numbers are\n"); for(i=0;i<j;i++) { printf("%d\n",b[i]); } printf("The odd numbers are\n"); for(i=0;i<k;i++) { printf("%d\n",c[i]); } getch(); }
      It will basically input an array of 'n' numbers and then separate it into two arrays, one contains odd numbers and one contains even numbers. Hoping to hear from you soon.
        I would change your program to this one:
        #!/usr/bin/perl use warnings; use strict; print 'Enter the number of elements: '; my $n = <>; # Read the input. chomp $n; # Remove the newline. print "Enter $n numbers.\n"; my @a; for (1 .. $n) { push @a, scalar <>; # Push numbers to the +array. } chomp @a; # Remove the newlines. print join (' ', 'The even numbers are:', grep $_ % 2, @a), # grep filters the num +bers = 1 modulo 2 "\n"; print join (' ', 'The odd numbers are:', grep 1 - $_ % 2, @a), "\n";
        Not really similar, is it? The main differences:
        • No main function needed.
        • Variables are declared where needed.
        • The diamond operator is used to read from the input.
        • for can be used with simpler syntax, avoiding off by 1 errors (see perlsyn)
        • grep can be used to filter arrays. No need for temporary variables to keep the results if you do not need them later.
        لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        use strict; # #include<conio.h> #void main() #{ my (@a,@b,@c,$i,$j,$k,$n); print("Enter the number of elements\n"); $n = <>; printf("Enter %d numbers\n",$n); for($i=0;$i<$n;$i++) { push @a, scalar(<>); } for($i=0;$i<$n;$i++) { if(($a[$i]%2)==0) { $b[$j]=$a[$i]; $j++; } else { $c[$k]=$a[$i]; $k++; } } print("The even numbers are\n"); for($i=0;$i<$j;$i++) { printf("%d\n",$b[$i]); } printf("The odd numbers are\n"); for($i=0;$i<$k;$i++) { printf("%d\n",$c[$i]); } <>; #}

        Not that this was the best (or even just a particularly good) way to write this, but it's the minimal change. Huge difference from the C code, right?

        Enoch was right!
        Enjoy the last years of Rome.

Re: New student, can we write this program in perl...
by zentara (Archbishop) on Oct 20, 2012 at 09:24 UTC
      Obviously it already did. Now that they've got the lowest bid from NASA, they're trying to figure out how to do it. But they're cheaper, nonetheless.
Re: New student, can we write this program in perl...
by aaron_baugher (Curate) on Oct 19, 2012 at 19:47 UTC

    See if your "teacher" likes this method:

    #!/usr/bin/env perl use Modern::Perl; my @n = (1..100); my @e; my @o; map { push @{($_ % 2 ? \@o : \@e)}, $_ } @n; say for @e;

    Here's another:

    #!/usr/bin/env perl use Modern::Perl; my @n = (1..100); my @o = sort { $a % 2 - $b % 2 } @n; my @e = splice @o, 0, @o/2, (); say for @e;

    Aaron B.
    Available for small or large Perl jobs; see my home node.

Re: New student, can we write this program in perl...
by tobyink (Abbot) on Oct 19, 2012 at 21:00 UTC

    There was recently a thread on the odd/even topic here: Subroutine Even/Odd.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: New student, can we write this program in perl...
by clueless newbie (Chaplain) on Oct 19, 2012 at 18:17 UTC

    Depending on how you interpret "two different arrays" the following might be acceptable,

    #!/usr/bin/perl use strict; use warnings; my $number; # use grep to accept only the integers push(@{$number->[$_ % 2]},$_) for (grep { m{^-?\d+$} } @ARGV); # Using $" to insert ", " local $"=', '; print "The even numbers are @{$number->[0]}\n"; print "while the odd numbers are @{$number->[1]}.\n";
    > perl 1 2 -nogo 3.4 3 4 5 -4 The even numbers are 2, 4, -4 while the odd numbers are 1, 3, 5.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://999976]
Approved by blue_cowdawg
[PriNet]: go figure, i just tried that, it retains some of the values (not the key) of the pre-assigned value
[PriNet]: i guess i'll just have to use two seperate hashes, there are two, but one is larger than the other, and when i reference the smaller one, it holds onto the values that were assigned to the larger hash (the keynames change, but unless i reassign a new valu

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2017-06-28 02:58 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (619 votes). Check out past polls.