Search code examples
perlsubroutine

What is the difference when calling subroutine with and without & in Perl?


For my homework, I was told to make a subroutine within Perl, and when called with arguments in it, it would print the arguments. I did this and the second part of my homework was to call that first subroutine within the second one. So I did all this, but then the question was: try running the second subroutine with "&" while calling the first one, and without it and to write what is the difference in these two different calls. So subroutine seems to works perfectly in both cases, with and without, but I just don't know what it really changed, therefore i don't know what to write. Off topic, does my code look fine? Kinda first time coding in this Perl.

This is the code:

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;

show_args('fred','barney','betty');

show_args_again();

sub show_args{
    my ($broj1, $broj2, $broj3) = @_;
    print "The arguments are: " . "$broj1, " . "$broj2, " . "$broj3.\n";
}
sub show_args_again{
    &show_args('fred','barney','betty');
}

Solution

  • Does the assignment say whether show_args_again should be called with parameters?

    The only thing I can think of that you are meant to discover is demonstrated by this code. Give it a try

    #!/usr/bin/perl
    
    use 5.010;
    use strict;
    use warnings;
    
    show_args('fred', 'barney', 'betty');
    print "---\n";
    show_args_again('fred', 'barney', 'betty');
    
    sub show_args{
        my ($broj1, $broj2, $broj3) = @_;
        no warnings 'uninitialized';
        print "The arguments are: $broj1, $broj2, $broj3.\n";
    }
    
    sub show_args_again {
        show_args(@_);
        &show_args(@_);
        show_args();
        &show_args();
        show_args;
        &show_args;
    }