Search code examples
perlsubroutine

Call subroutine from subroutine


I have a subroutine (in Perl) that needs to make a call to another one transfering its arguments and also adding a string. I have tried something like this (but I'm looking for THE answer, not just correcting this ...):

sub TestBase($)
{
    print @_;
    return 'hard processed string';
}

sub Test($)
{
    print @_;
    return TestBase(@_, 'Filename.txt');
}

This one fails with "Too many arguments for main::TestBase" (all these years and I still use cmd.com, no easy copy-paste in this case!).


Solution

  • To clarify and summarize my corrections to Dan's answer, this is what your code should look like.

    I've removed the subroutine prototypes, put the open braces on the same line as the subroutine name (as preferred by perldoc perlstyle), changed the names to lower-case (upper case is generally reserved for global variables such as package names), and removed the return keyword.

    Note that you would probably be best leaving the subroutine names as they are, especially if other people are writing code that depends on them. Following accepted practice is important, but not as important as keeping the interface to an existing code base static.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    sub test_base {
      print @_;
      'hard processed string';
    }
    
    sub test {
      print @_;
      test_base(@_, 'Filename.txt');
    }
    
    my $retval = test('A', 'B', 'C');
    print "\n\n", $retval, "\n";
    

    output

    ABCABCFilename.txt
    
    hard processed string