One useful way to think of a module is as a collection of related subroutines. They should be designed to be easy to use by any programmer without regards to the internals. Now think about a script which looks like this:
#!/usr/bin/perl use warnings; use strict; my @files = find_files(shift); foreach my $file (@files) { eval { process_file($file) }; die "Could not process $file: $@" if $@; } sub find_files { .... } sub process_file { .... }
With that, you have reused whatever code you have in &process_file. That's good. But what if another program needs the same functionality?
package My::FileProcessor; use strict; use warnings; use base 'Exporter'; our @EXPORT_OK = qw(find_files process_file); sub find_files { .... } sub process_file { .... } 1;
And your original code becomes this:
#!/usr/bin/perl use warnings; use strict; use My::FileProcessor qw(find_files process_file); my @files = find_files(shift); foreach my $file (@files) { eval { process_file($file) }; die "Could not process $file: $@" if $@; }
That code is now shorter, but more importantly, other programs can more easily share the functionality provided by My::FileProcessor.
Does that help?
In reply to Re: Subroutines vs Modules
by Ovid
in thread Subroutines vs Modules
by sub_chick
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |