Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Perl : Convert a monolithic code to a function

by user786 (Sexton)
on Jun 28, 2014 at 22:59 UTC ( [id://1091587]=perlquestion: print w/replies, xml ) Need Help??

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

Hello, I have written a perl script that reads information form text file and executes some commands.
use strict; use warnings; use autodie; use Net::SSH::Expect; # ssh into a router my $ssh = Net::SSH::Expect->new( host => "ipaddr", password => 'user', user => 'pwd', raw_pty => 1, ); my $login_output = $ssh->login(); # execute the commands $ssh->exec("command 1"); $ssh->exec("command 2"); # open a file and read the config information open my $prep, '<', 'config.txt; while (my $config = <$prep>) { chomp $config; my $conf = $ssh->exec("$config"); print("$conf"); }

the above code works and provides the required output. However i would like to convert this code into a function so that i can reuse this for various config files.

For instance: If I make the following function call  config_function("config2.txt"); The script should read that 2nd config file and execute the commands.Is it possible to do that.? suggestions please.

Replies are listed 'Best First'.
Re: Perl : Convert a monolithic code to a function
by 1s44c (Scribe) on Jun 28, 2014 at 23:26 UTC
    sub mysub { my ( $var1, $var2 ) = @_; rest of your process } Call with: mysub($var1, $var2);

    It's all in the learning perl book, it's probably easiest to start there.

    EDIT: No ampersand before the subroutine's name!

      This is what i tried ,when i compile the code it doesn't throw an error.But it is not working, Am i missing something here?
      sub mysub { my ($var1) = @_; $ssh->exec("cmd1"); $ssh->exec("cmd2"); open my $prep, '<', $var1; while (my $config = <$prep>) { chomp $config; my $conf = $ssh->exec("$config"); print("$conf"); } mysub("config.txt");

      Thanks for the reply. Pardon my ignorance. 1)Does $var1, $var 2 refer to the config file ? 2)And why & before mysub &mysub($var1, $var2);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1091587]
Approved by farang
Front-paged by boftx
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-03-29 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found