[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] subroutine parameters - elementary question



At 22:18 -0400 5/4/99, Noe Dinnerstein:  President, BodhiSoftWare wrote:
> I'm having dificulty getting the correct syntax for passing and using a
> filename as a parameter to a subroutine which will then open and read it.
> I have be fiddling with different ways to deal with scope, but this is
> fairly new territory for me and I'm probably overlooking something
> obvious....
>

First off, subroutines are defined as

  sub foo {         # without protptypes
   ...
  }

or
  sub foo($$) {      # with prototypes that specify required argument type
     ...
  }
or
  sub foo() {       # with prototype that specifies - No Arguments!
     ...
  }

but never as
 sub SearchFile(main::$newfile, $dlg->item_text(4))
   # this is using pseudo-C syntax


Ways to do it:
1) You can pass in the filename

        foreach my $newfile(@newfiles) {
           SearchFile($newfile, $dlg->item_text(4))
           ...
        }

sub SearchFile {
   my $filename = shift;
   my item_text = shift;

   open(IN, $filename);
   ...
}

There's no need to fully qualify the filename variable if you've passed it
to the subroutine. Besides, the qualification is a package qualification.
If you're just using a subroutine in the same file you're in the same
package.

2) You can make $newfile a global variable and not bother to pass it
around. Add

   use vars qw/$newfile/

after all the other "use" directives.


3) You could also open the file in the "main" routine and pass (a reference
to) the filehandle to the function (actually you pass a reference to the
typeglob that includes the filehandle.)

WARNING - Idiom Alert - Here There Be Dragons! - Heavy Magic Ahead

  open(IN, $newfile);
  SearchFile(\*IN, $dlg->item_text(4));
  ...

sub SearchFile {
  my $filehandle = shift;
  my $item_text = shift;

  # now treat $filehandle _exactly_ as you would treat IN
  ...
}
-- --
       |\      _,,,---,,_       Vicki Brown <vlb@cfcl.com>
 ZZZzz /,`.-'`'    -.  ;-;;,_   Journeyman Sourceror: Scripts & Philtres
      |,4-  ) )-,_. ,\ (  `'-'  P.O. Box 1269  San Bruno  CA  94066
     '---''(_/--'  `-'\_) http://www.cfcl.com/~vlb  http://www.macperl.org

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org