Writing a Perl function

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.


  • 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)

    sub my_subroutine {

    print join(" ", @_);

    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

  • 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];

    # @_ <-----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.

Howdy, Stranger!

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