yoda54 has asked for the wisdom of the Perl Monks concerning the following question:

Hey monks,

What's better way to write this? I need something that will execute the right function based on the number of inputs. Eventually, what is a way to do this for N inputs?

Thanks for any help!

sub input { if ( $_[0] =~ /(.+)\s+(.+)\s+(.+)/) { print "3 params\n"; } elsif ( $_[0] =~ /(.+)\s+(.+)/) { print "2 params\n"; } elsif ( $_[0] =~ /(.+)/) { print "1 params\n"; } }

Replies are listed 'Best First'.
Re: Perl newbie question.
by Ratazong (Monsignor) on Mar 16, 2010 at 09:53 UTC

    You could try to split your parameter and access the number of elements ... something like this:

    my @nr = split (/\s+/, $_[0]); print ($#nr+1, " params \n");

    However you might want to do some fine-tuning ... the code above won't work correctly for parameters starting with whitespaces

    HTH, Rata

    update: or as an one-liner: print (scalar(split (/\s+/, $_[0])), " params \n");

      my $nr = split (/\s+/, $_[0]);

      We can get the number of elements by simply assigning the return value of split into a scalar variable.

      Example
      $str="1:3:4:5"; my $num=split(':',$str); print "Num:$num";

      $num will contain '4'.
Re: Perl newbie question.
by Utilitarian (Vicar) on Mar 16, 2010 at 09:57 UTC
    This does what you want
    $ perl -e 'use strict; sub input{ my (@params) = $_[0] =~ m/([\S]+)/g; print scalar @params ," parameters supplied\n"; } input(join " ", @ARGV); ' Fear Anger Hate Darkside 4 parameters supplied
    Update: Changed \w to \S as original question was split on multiple space characters (thanks to cdarke for spotting this) and modified argument list.

    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
Re: Perl newbie question.
by JavaFan (Canon) on Mar 16, 2010 at 11:23 UTC
    Unless your question is actually about Perl newbies, you shouldn't title your questions "Perl newbie question". A title is a short ad, which should attract people to your question that can provide useful answers. You are doing yourself a disfavour.
Re: Perl newbie question.
by jethro (Monsignor) on Mar 16, 2010 at 10:00 UTC
    Are you sure all your params are concatenated in a string? Parameters from the command line were already splitted into separate values when the perl script starts. And function parameters stay separated if they were when you called the function. In those cases a simple  scalar @_ will tell you the number of parameters.