#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2011
    Posts
    2
    Rep Power
    0

    How to write a switch statement in perl


    Hello I have written a perl code using nested if statements but i want to use switch function insted of nestedif



    #!/usr/bin/perl


    print "Enter the Integers";

    my $Integers =<>;

    my @numbers =split(',',$Integers);



    foreach my $num (@numbers)
    {
    is_inum($num);
    print "@letters"
    }



    sub is_inum
    {
    print "$num\n";
    my ($inum)=shift(@_);


    if ($inum == 2)
    {
    @letters = (a,b,c);
    return @letters;
    }
    elsif($inum == 3)
    {
    @letters = (d,e,f);
    return @letters;
    }


    }





    thanx in advance

    BR,
    kumar
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2011
    Posts
    2
    Rep Power
    0
    Have written this code but it's not working

    please help me....


    #!/usr/bin/perl

    use Switch;
    print "Enter the Integers";

    my $Integers =<>;

    my @numbers =split(',',$Integers);


    foreach my $num (@numbers)
    {
    $alpha =is_inum($num);
    print "$alpha";
    }







    sub is_inum
    {
    my ($inum)=shift(@_);
    switch ($inum) {
    case 2 { return 'abc' ;}
    case 3 { return 'def' ;}
    }
    }
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2007
    Posts
    765
    Rep Power
    930
    Please use [code][/code] tags around source code to make it legible.

    Also your question is answered in perlfaq7. Perl has really good documentation, investing the time to understand how it's organized is well worth it.

    To summarize the faq:
    If you're using perl 5.10 or better: perldoc perlsyn
    If you're using perl 5.8: Switch module
    sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);

IMN logo majestic logo threadwatch logo seochat tools logo