Loading ...
Sorry, an error occurred while loading the content.
 

Subroutines

Expand Messages
  • ROB Technology
    Ok. Judging by my other emails, etc., you can probably tell I m just starting out with perl. I can write a lot of scripts, etc. But one thing that s caught my
    Message 1 of 13 , Feb 17, 2002
      Ok. Judging by my other emails, etc., you can probably tell I'm just
      starting out with perl. I can write a lot of scripts, etc. But one thing
      that's caught my mind is subroutines.
      What are they?
      How do they work?
      What are they for?
      What's the coding for them?

      Thanks for anyone who can help me answer these questions. :-)
      -Rob
    • b_harnish
      ... just ... one thing ... Subroutines are exactly what the name implies: sub routines. You may call a program/script a routine, because it doesn t change, it
      Message 2 of 13 , Feb 17, 2002
        --- In perl-beginner@y..., "ROB Technology" <rob@r...> wrote:
        > Ok. Judging by my other emails, etc., you can probably tell I'm
        just
        > starting out with perl. I can write a lot of scripts, etc. But
        one thing
        > that's caught my mind is subroutines.
        > What are they?

        Subroutines are exactly what the name implies: sub routines. You
        may call a program/script a routine, because it doesn't change,
        it just does the same thing (much like a dance routine, or a
        figure skating routine). A subroutine, is a smaller version of
        that. Subroutines need a main-routine to be useful.

        > How do they work?

        Execution of the current (sub)routine pauses when you call a
        subroutine. Execution starts at the top of the subroutine, and
        flows through it until its done. Then execution resumes from
        where it left off. You can pass parameters to the subroutines to
        get them to do different things. They can return values to the
        caller (these are usually called functions).

        > What are they for?

        Hmm, programs have long wondered this. Some believe in different
        theories. Some believe the main routine should just loop through
        calling subroutines. Some that the meat of the code should be in
        the main routine, subroutines are just for helping the main
        routine. Perhaps you might want one to simplify calculations,
        such as the area of a circle:
        print "If the radius=5, the area=", circleArea(5), "\n";
        sub circleArea {
        my $radius = shift();
        my $PI = 3.141592;
        return (2*$PI*$radius);
        };

        Using subroutines makes programs easier to read, such as:
        # printError, verifyItemExists, getCurrentPrice,
        # adjustPriceForSales are all subroutines
        for (@{$cart->{ items }}) {
        printError("Item doesn't exist!")
        unless verifyItemExists($_);
        getCurrentPrice($_);
        adjustPriceForSales($_);
        }

        > What's the coding for them?

        see perlsub.

        - Brian
      • Rick
        Ok, I m not proud...I am pretty much baffled by subroutines...especially when you make them local with my (i.e. if the functions are local to the block, how
        Message 3 of 13 , Nov 10, 2002
          Ok, I'm not proud...I am pretty much baffled by
          subroutines...especially when you make them local with "my" (i.e. if
          the functions are local to the block, how can the rest of the code
          read into them for information??).
          Anyway, below is my code...can someone help me out with this please?

          #!/usr/bin/perl
          #converts Fahrenheit Temp to Celsius, Rankine, and Kelvin
          #main code calls first 3 functions
          #first function obtains deg fah from user
          #second function converts fah into cel, ran, & kel
          #third function prints temp for all 4 scales
          #second function calls a 4th function 3 times,
          #whereby the fourth functions rounds all to 1 decimal place precision

          use warnings;
          use strict;

          fah();

          second_function();

          third_function();

          fourth_function();


          sub fah
          {
          print ("Enter a temperature in deg Fahrenheit \n");
          chomp ($_ = <>);

          }

          sub second_function
          {

          my $cel = (@_ -32) * 100 /180;

          my $ran = ($_ -32) + 491.69;

          my $kel = ($_ -32) *100 /180 +273.16;

          my $rounded = int ($_ * 10 + .5) /10;

          return ($cel,$ran,$kel,$rounded);
          }

          sub third_function
          {


          print ("FAHRENHEIT: $_ \n\n");
          print ("CELCIUS: $_ \n\n");
          print ("RANKINE: $_ \n\n");
          print ("KELVIN: $_\n\n");

          }

          sub fourth_function
          {

          print ("ROUNDED: $rounded \n\n");

          return ($rounded);
          }
        • Charles K. Clarkson
          ... Perl has a mechanism for sending information into a subroutine and a mechanism for returning values. Let s look at third_function, which needs information
          Message 4 of 13 , Nov 10, 2002
            Rick [rshrum@...] asked:

            : Ok, I'm not proud...I am pretty much baffled by
            : subroutines...especially when you make them local
            : with "my" (i.e. if the functions are local to the
            : block, how can the rest of the code read into
            : them for information??). Anyway, below is my code
            : ...can someone help me out with this please?

            Perl has a mechanism for sending information
            into a subroutine and a mechanism for returning
            values. Let's look at third_function, which needs
            information passed in but not out.

            third_function();
            sub third_function {
            print "FAHRENHEIT: $_ \n\n";
            print "CELCIUS: $_ \n\n";
            print "RANKINE: $_ \n\n";
            print "KELVIN: $_\n\n";
            }

            We pass a list into a sub inside the parenthesis.

            third_function( $fahrenheit, $celsius, $rankine, $kelvin );


            The default array: @_ is used to retrieve a list
            of values sent to a subroutine:

            sub third_function {
            my( $fahrenheit, $celsius, $rankine, $kelvin ) = @_;
            print "FAHRENHEIT: $fahrenheit\n\n";
            print "CELCIUS: $celsius\n\n";
            print "RANKINE: $rankine\n\n";
            print "KELVIN: $kelvin\n\n";
            }

            But what if we need to get something out of a sub?
            "return" gets us half way there. We need something to
            receive what is returned.

            my( $celsius, $rankine, $kelvin, $rounded ) =
            second_function( $fahrenheit );

            Here $fahrenheit is passed to the sub and a list
            of variables are retrieved from the sub. Note that
            the variable names retrieved does not match need to
            match the names sent by the sub.

            sub second_function {
            my $fahrenheit = shift @_;
            my $cel = ( $fahrenheit - 32 ) * 100 / 180;
            my $ran = ( $fahrenheit - 32 ) + 491.69;
            my $kel = ( $fahrenheit - 32 ) * 100 / 180 + 273.16;
            my $rounded = int( $fahrenheit * 10 + .5 ) / 10;
            return ( $cel, $ran, $kel, $rounded );
            }


            HTH,

            Charles K. Clarkson
            --
            Head Bottle Washer,
            Clarkson Energy Homes, Inc.
            254 968-8328
          • Rick
            Charles, Thanks so much for your help. You were very generous of your time, and I appreciate it. I do not know why I have such a time with subroutines. Anyway,
            Message 5 of 13 , Nov 11, 2002
              Charles,
              Thanks so much for your help. You were very generous of your time,
              and I appreciate it.
              I do not know why I have such a time with subroutines.
              Anyway, I have just the $rounded function to do for the program so I
              will try to see if I can make any sense of that. Heehee...

              Take care,
              Rick
            • prakash@foothill.net
              Charles is one of the very generous guy in giving advice.. only once he asked a question about wait !! at that time i looked some article but could not find
              Message 6 of 13 , Nov 11, 2002
                Charles is one of the very generous guy in giving advice..
                only once he asked a question about wait !! at that time
                i looked some article but could not find any solution for
                his question !!! .. but lots of time he answered !! nice
                to see those kind of people !!

                Perl Rocks



                ----- Original Message -----
                From: "Rick" <rshrum@...>
                To: perl-beginner@yahoogroups.com
                Sent: Tue, 12 Nov 2002 02:21:45 -0000
                Subject: Re: [PBML] Subroutines & rounding

                > Charles,
                > Thanks so much for your help. You were very generous of your time,
                > and I appreciate it.
                > I do not know why I have such a time with subroutines.
                > Anyway, I have just the $rounded function to do for the program so I
                > will try to see if I can make any sense of that. Heehee...
                >
                > Take care,
                > Rick
                >
                >
                >
                > Unsubscribing info is here: http://help.yahoo.com/help/us/groups/groups-32.html
                >
                > Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
                >
                >
                > ______________________________________________________
                > This email was pre-scanned by Spam Guardian
                > A Service Provided by www.foothill.net and FNFmail.com
                -----------------------------------------------
                This email was brought to you by Foothill.net
                http://webmail.foothill.net/user/login.cgi
              • Rick
                That s cool. If I don t get discouraged with trying to learn Perl, I would like to someday be someone who offers advice here once in awhile, instead of always
                Message 7 of 13 , Nov 12, 2002
                  That's cool. If I don't get discouraged with trying to learn Perl, I
                  would like to someday be someone who offers advice here once in
                  awhile, instead of always asking the questions! hehe...


                  --- In perl-beginner@y..., prakash@f... wrote:
                  > Charles is one of the very generous guy in giving advice..
                  > only once he asked a question about wait !! at that time
                  > i looked some article but could not find any solution for
                  > his question !!! .. but lots of time he answered !! nice
                  > to see those kind of people !!
                  >
                  > Perl Rocks
                  >
                  >
                  >
                  > ----- Original Message -----
                  > From: "Rick" <rshrum@c...>
                  > To: perl-beginner@y...
                  > Sent: Tue, 12 Nov 2002 02:21:45 -0000
                  > Subject: Re: [PBML] Subroutines & rounding
                  >
                  > > Charles,
                  > > Thanks so much for your help. You were very generous of your
                  time,
                  > > and I appreciate it.
                  > > I do not know why I have such a time with subroutines.
                  > > Anyway, I have just the $rounded function to do for the program
                  so I
                  > > will try to see if I can make any sense of that. Heehee...
                  > >
                  > > Take care,
                  > > Rick
                  > >
                  > >
                  > >
                  > > Unsubscribing info is here:
                  http://help.yahoo.com/help/us/groups/groups-32.html
                  > >
                  > > Your use of Yahoo! Groups is subject to
                  http://docs.yahoo.com/info/terms/
                  > >
                  > >
                  > > ______________________________________________________
                  > > This email was pre-scanned by Spam Guardian
                  > > A Service Provided by www.foothill.net and FNFmail.com
                  > -----------------------------------------------
                  > This email was brought to you by Foothill.net
                  > http://webmail.foothill.net/user/login.cgi
                • Octavian Rasnita
                  Hi all, I would like to do something like: URL: foreach my $var1(@vars) { &sub1($var1); } sub sub1 { my $var1 = shift; &sub2(var1); } sub sub2 { my $var1 =
                  Message 8 of 13 , Jan 3, 2003
                    Hi all,

                    I would like to do something like:

                    URL: foreach my $var1(@vars) {
                    &sub1($var1);
                    }

                    sub sub1 {
                    my $var1 = shift;
                    &sub2(var1);
                    }

                    sub sub2 {
                    my $var1 = shift;
                    if ($var1 == 3) {
                    next URL;
                    }
                    }

                    It doesn't work because I guess the "next" function can't work to get out of
                    the subroutines.
                    I also tried using the "goto" function but with the same result.

                    Thank you for help.

                    Teddy,
                    Teddy's Center: http://teddy.fcc.ro/
                    Email: orasnita@...
                  • prakash
                    how about this ?? &sub4; sub sub4{ foreach my $var1(@vars) { &sub1($var1); } } sub sub1 { my $var1 = shift; &sub2(var1); } sub sub2 { my $var1 = shift; if
                    Message 9 of 13 , Jan 3, 2003
                      how about this ??

                      &sub4;

                      sub sub4{
                      foreach my $var1(@vars) {
                      &sub1($var1);
                      }
                      }

                      sub sub1 {
                      my $var1 = shift;
                      &sub2(var1);
                      }

                      sub sub2 {
                      my $var1 = shift;
                      if ($var1 == 3) {
                      &sub4;
                      }
                      }

                      > -----Original Message-----
                      > From: Octavian Rasnita [mailto:orasnita@...]
                      > Sent: Friday, January 03, 2003 6:31 AM
                      > To: perl-beginner@yahoogroups.com
                      > Subject: [PBML] Subroutines
                      >
                      >
                      > Hi all,
                      >
                      > I would like to do something like:
                      >
                      >
                      >
                      > It doesn't work because I guess the "next" function can't work to
                      > get out of
                      > the subroutines.
                      > I also tried using the "goto" function but with the same result.
                      >
                      > Thank you for help.
                      >
                      > Teddy,
                      > Teddy's Center: http://teddy.fcc.ro/
                      > Email: orasnita@...
                      >
                      >
                      >
                      >
                      > Unsubscribing info is here:
                      http://help.yahoo.com/help/us/groups/groups-32.html

                      Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/


                      ______________________________________________________
                      This email was pre-scanned by Spam Guardian
                      A Service Provided by www.foothill.net and FNFmail.com
                    • Jenda Krynicky
                      From: Octavian Rasnita ... They opened this years obfuscation contest already? :-) Just don t do that. Goto s should be considered
                      Message 10 of 13 , Jan 3, 2003
                        From: "Octavian Rasnita" <orasnita@...>
                        > I would like to do something like:
                        >
                        > URL: foreach my $var1(@vars) {
                        > &sub1($var1);
                        > }
                        >
                        > sub sub1 {
                        > my $var1 = shift;
                        > &sub2(var1);
                        > }
                        >
                        > sub sub2 {
                        > my $var1 = shift;
                        > if ($var1 == 3) {
                        > next URL;
                        > }
                        > }
                        >
                        > It doesn't work because I guess the "next" function can't work to get
                        > out of the subroutines. I also tried using the "goto" function but
                        > with the same result.

                        They opened this years obfuscation contest already? :-)

                        Just don't do that.

                        "Goto's should be considered harmfull"

                        Jenda
                        ===== Jenda@... === http://Jenda.Krynicky.cz =====
                        When it comes to wine, women and song, wizards are allowed
                        to get drunk and croon as much as they like.
                        -- Terry Pratchett in Sourcery
                      • Hans Ginzel
                        ... What about return values? foreach my $var1 (@vars) { sub1($var1) and next; } sub sub1 { my $var1 = shift; sub2(var1) and return 1; # I expect some code
                        Message 11 of 13 , Jan 3, 2003
                          On Fri, Jan 03, 2003 at 04:31:19PM +0200, Octavian Rasnita wrote:
                          > I would like to do something like:

                          What about return values?

                          foreach my $var1 (@vars) {
                          sub1($var1) and next;
                          }

                          sub sub1 {
                          my $var1 = shift;
                          sub2(var1) and return 1;
                          # I expect some code here...
                          return 0;
                          # If the sub2 calling is the last statement, write
                          # return sub2(var1);
                          # subroutine calling returns defautly value of the last statement,
                          # but _write_ return there, you know sub1 depends on what sub2
                          # returns --- someone is interested on return vale.
                          }

                          sub sub2 {
                          my $var1 = shift;
                          $var1 == 3 and retun 1
                          }

                          See also goto &sub, which is quite different then goto LABEL (perldoc -f goto).

                          Hans

                          --
                          You can find a Vim desktop calendar here: http://www.moolenaar.net/
                          Happy Vimming in 2003!
                        • Charles K. Clarkson
                          ... I assume you re leaving out a lot of the guts to your subs. How about: foreach my $var1 ( @vars ) { next unless sub1( $var1 ); . . . } sub sub1 { my $var1
                          Message 12 of 13 , Jan 3, 2003
                            Octavian Rasnita [mailto:orasnita@...] asked:

                            : I would like to do something like:
                            :
                            : URL: foreach my $var1(@vars) {
                            : &sub1($var1);
                            : }
                            :
                            : sub sub1 {
                            : my $var1 = shift;
                            : &sub2(var1);
                            : }
                            :
                            : sub sub2 {
                            : my $var1 = shift;
                            : if ($var1 == 3) {
                            : next URL;
                            : }
                            : }

                            I assume you're leaving out a lot of the guts to your
                            subs. How about:

                            foreach my $var1 ( @vars ) {
                            next unless sub1( $var1 );
                            .
                            .
                            .
                            }

                            sub sub1 {
                            my $var1 = shift;
                            return unless sub2( $var1 );
                            .
                            .
                            .
                            return 1; # or some result
                            }

                            sub sub2 {
                            my $var1 = shift;
                            return if $var1 == 3;
                            .
                            .
                            .
                            return 1; # or some result
                            }

                            If $var1 in sub2() is 3, sub1 returns undef
                            and we get the next $var1 in the foreach. Otherwise,
                            processing continues.


                            HTH,

                            Charles K. Clarkson
                            --
                            Head Bottle Washer,
                            Clarkson Energy Homes, Inc.
                            Mobile Home Specialists
                            254 968-8328
                          • Hans Ginzel
                            ... # I for got this here: return 0; ... Or what about eval? I learned here, it is commonly used for error ... eval { sub1($var1) }; next if $@; # or better
                            Message 13 of 13 , Jan 3, 2003
                              On Fri, Jan 03, 2003 at 06:24:50PM +0100, Hans Ginzel wrote:
                              > What about return values?
                              >
                              > foreach my $var1 (@vars) {
                              > sub1($var1) and next;
                              > }
                              >
                              > sub sub1 {
                              > my $var1 = shift;
                              > sub2(var1) and return 1;
                              > # I expect some code here...
                              > return 0;
                              > }
                              >
                              > sub sub2 {
                              > my $var1 = shift;
                              > $var1 == 3 and retun 1
                              # I for got this here:
                              return 0;
                              > }

                              Or what about eval? I learned here, it is commonly used for error
                              handling, but you can use it in this case as well:

                              > foreach my $var1 (@vars) {
                              eval { sub1($var1) };
                              next if $@;
                              # or better
                              next if $@ =~ /^my_flag$/;
                              > }
                              >
                              > sub sub1 {
                              > my $var1 = shift;
                              sub2(var1);
                              # ...
                              > }
                              >
                              > sub sub2 {
                              > my $var1 = shift;
                              $var1 == 3 and die "my_flag\n"; # be careful on "\n" here
                              > }


                              Note the differnce between eval "string" and eval { code; };
                              Note the last semicolon is important, see perldoc -f eval.

                              Best regards
                              Hans

                              --
                              http://www.apmaths.uwo.ca/~xli/vim/vim_tutorial.html
                            Your message has been successfully submitted and would be delivered to recipients shortly.