Writing a Perl function - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Writing a Perl function

gurujiguruji Posts: 12Member
Can someone show me a perl function that takes any number of arguments. The function shall also print the arguments on a single line, with arguments seperated by one space.

Thanks in advance.

Comments

  • entitledXentitledX Posts: 25Member
    Alright no problem, so I'll just start off with the code.

    [code]#!/usr/bin/perl -w

    sub my_subroutine {

    my $a = shift;
    my $b= shift;

    print "$a $b";


    }

    my_subroutine("First Arguement", "Second Argument");[/code]


    Ok, so here we declare the subroutine using the operator [b]sub[/b] and we put our code inside the curly braces. All arguments
    given when we call the subroutine are stored inside the array @_. When we shift we just take the first element inside that array. And finally we print it out split by a space. Now this is all fine and dandy, but let's shorten it up a bit, after all isn't perl here to make easy jobs easier? ;o)

    [code]
    sub my_subroutine {

    print join(" ", @_);
    }[/code]

    In the first example we only took the first two arguments (I wanted to include the first example just to show how to get the values of the arguments), but now, we can give the subroutine as many arguments as we want and it'll print each one of them out split by spaces.

    I hope this answers your question. Later!



    --
    You see things; and you say "Why"
    But I dream things that never were; and I say "Why not?"

    -- George Bernard Shaw



  • DrGonzoDrGonzo Posts: 41Member
    Unless specified otherwise, you can send any Perl function(sub) any number of values.

    Heres another method of getting whats passed to a function(sub)


    sub GetSomeValues
    {
    my $FirstValue = $_[0];
    my $SecondValue = $_[1];
    my $ThirdValue = $_[2];
    etc...
    etc...
    etc...
    }

    # @_ <-----Thats what the above is indexing, its the variable list.

    And it holds all sorts a values (like references to variables or file handles and also simple values like numbers and characters....but thats sorta obvious 'cause it's an array)
Sign In or Register to comment.