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

Re: [PBML] returning arrays and hashes from a subroutine

Expand Messages
  • Charles K. Clarkson
    ... So this is what Japhy meant. Shame on you Japhy, I can t believe you d let Mark do it this way. :) ... my $sql = SELECT doc_name FROM $table WHERE
    Message 1 of 12 , May 2, 2002
    • 0 Attachment
      "markveerman" <mark@...> wrote:

      : I figured it out! Although, I don't really understand the, but
      : here's what it was:
      :
      : Below within the sub I originally had: my @fieldnames = $db-
      : >FieldNames(); return @fieldnames; When I removed the word "my",
      : @fieldnames was returned correctly. Also, I didn't realize you could
      : call the function like @array = function() - so that was helpful too.
      :
      : thanks for your help japhy!

      So this is what Japhy meant. Shame on you Japhy, I
      can't believe you'd let Mark do it this way. :)

      : use Win32::ODBC;
      : my $dsn = "mysql";
      : my $table = "table";
      : my $sql = "SELECT doc_name FROM " . $table . " WHERE status = 'Q'";

      my $sql = "SELECT doc_name FROM $table WHERE status = 'Q'";

      : odbc($dsn, $table, $sql);

      my @field_names = odbc($dsn, $sql) ||
      die "There's an uncaught error in odbc()";

      : foreach $fieldnames(@fieldnames){
      : print $fieldnames . "\n";
      : }

      print "$_\n" foreach @field_names;

      : sub odbc {
      : my ($dsn, $table, $sql) = @_;
      : use Win32::ODBC;

      sub odbc {
      my ($dsn, $sql) = @_;

      : my $db = new Win32::ODBC($dsn);
      :
      : if (!$db){
      : die "Error connecting: " . Win32::ODBC::Error() . "\n";
      : }

      my $db = new Win32::ODBC($dsn) ||
      die 'Error connecting: ', Win32::ODBC::Error();

      : if ($db->Sql($sql)) {
      : print "Error submitting SQL statement: " . $db->Error
      : () . "\n" . $sql;
      : }

      if ( $db->Sql($sql) ) {
      print "Error submitting SQL statement: $db->Error\n$sql";
      # Are you sure you don't want to die here?
      }

      : else{
      : @fieldnames = $db->FieldNames();
      : return @fieldnames;

      return $db->FieldNames();
      : }

      return;


      HTH,

      Charles K. Clarkson
      --
      Head Bottle Washer,
      Clarkson Energy Homes, Inc.

      CJ Web Work - Domains for Real Estate Investors.
      E Pluribus Unum -- One from many.
    • Charles K. Clarkson
      ... When I started with perl last year, almost everything I managed to get working was an example of poor coding. A subroutine should be able to be pulled out
      Message 2 of 12 , May 2, 2002
      • 0 Attachment
        "markveerman" <mark@...> wrote:

        : Thanks Charles - Are you telling me that even though it
        : works it's not good code? :-).

        When I started with perl last year, almost everything I
        managed to get working was an example of poor coding.
        A subroutine should be able to be pulled out of the
        program it was written in and placed in another and run
        with minimal adjustment.

        When writing a subroutine, think of it as if a manager
        just handed you an assignment. You have no idea how this
        sub will be used in the program. You know what it should
        accept, what it should return, and what it should do.

        You can cut some corners for short programs, but the
        larger and more complex your script gets the more you
        need to follow this or a more refined approach to
        building subroutines.

        : As if it's not totally obvious - I'm a novice.

        A novice what?

        : > So this is what Japhy meant. Shame on you Japhy, I
        : > can't believe you'd let Mark do it this way. :)
        :
        : In defense of Japhy, today was the first day I've ever
        : written a sub routine, so the issues with scoping and
        : local/global variables is entirely new.

        Is was meant as a joke. I knew Japhy didn't mean want
        you thought he did.


        HTH,

        Charles K. Clarkson
        --
        Head Bottle Washer,
        Clarkson Energy Homes, Inc.

        CJ Web Work - Domains for Real Estate Investors.
        E Pluribus Unum -- One from many.
      • markveerman
        Hello, How do you return an array or a hash from a subroutine? If I print the data from the array within the sub, everything works fine. I think the problem
        Message 3 of 12 , May 2, 2002
        • 0 Attachment
          Hello,
          How do you return an array or a hash from a subroutine? If I print
          the data from the array within the sub, everything works fine. I
          think the problem has something to do with the type of array I'm
          trying to return - but I'm a new programmer so I'm a bit confused.
          Thanks in advance for any help!
          /mark

          Here's the sub
          <snip>
          sub odbc {
          my ($dsn, $table, $sql) = @_;
          use Win32::ODBC;
          my $db = new Win32::ODBC($dsn);
          if (!$db){
          die "Error connecting: " . Win32::ODBC::Error
          () . "\n";
          }
          if ($db->Sql($sql)) {
          print "Error submitting SQL statement: " . $db-
          >Error ) . "\n" . $sql;
          }
          my @fieldnames = $db->FieldNames();
          return @fieldnames;
          }
          </snip>
        • Jeff 'japhy' Pinyan
          ... You ve shown the function, but not what you re doing with it. Here s a brief example: sub get_lengths { my @len; for my $str (@_) { push @len, length
          Message 4 of 12 , May 2, 2002
          • 0 Attachment
            On May 2, markveerman said:

            >How do you return an array or a hash from a subroutine? If I print
            >the data from the array within the sub, everything works fine. I
            >think the problem has something to do with the type of array I'm
            >trying to return - but I'm a new programmer so I'm a bit confused.

            You've shown the function, but not what you're doing with it. Here's a
            brief example:

            sub get_lengths {
            my @len;
            for my $str (@_) {
            push @len, length $str;
            }
            return @len;
            }

            @lengths = get_lengths("this", "that", "the other thing");

            --
            Jeff "japhy" Pinyan japhy@... http://www.pobox.com/~japhy/
            RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
            ** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
            <stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
            [ I'm looking for programming work. If you like my work, let me know. ]
          • markveerman
            ... I m trying to write a function that that will use the Win32::ODBC module to query a database and return an array containing the fieldnames of the
            Message 5 of 12 , May 2, 2002
            • 0 Attachment
              > You've shown the function, but not what you're doing with it.

              I'm trying to write a function that that will use the Win32::ODBC
              module to query a database and return an array containing the
              fieldnames of the recordset, and also a hash with the data.

              If I use the following within the sub routine:

              <snip>
              my @fieldnames = $db->FieldNames();
              foreach $fieldnames(@fieldnames){
              print $fieldnames . "\n";
              </snip>

              It works fine, so I know that $fieldnames is a working array, but
              when I try to use return @fieldnames; and put the foreach loop
              outside of the function I get nothing.

              Does it have something to do with the type of array or the format of
              the data in the array? I tried your sample and that worked fine. Am
              I missing something obvious?
              thanks,
              /mark
            • Jeff 'japhy' Pinyan
              ... You re returning the array, but what are you returning it TO? ... I think so. My code stores the return value of the function: @output = function(); Does
              Message 6 of 12 , May 2, 2002
              • 0 Attachment
                On May 2, markveerman said:

                >> You've shown the function, but not what you're doing with it.
                >
                >If I use the following within the sub routine:
                >
                ><snip>
                >my @fieldnames = $db->FieldNames();
                >foreach $fieldnames(@fieldnames){
                >print $fieldnames . "\n";
                ></snip>
                >
                >It works fine, so I know that $fieldnames is a working array, but
                >when I try to use return @fieldnames; and put the foreach loop
                >outside of the function I get nothing.

                You're returning the array, but what are you returning it TO?

                >Does it have something to do with the type of array or the format of
                >the data in the array? I tried your sample and that worked fine. Am
                >I missing something obvious?

                I think so. My code stores the return value of the function:

                @output = function();

                Does yours? You still haven't shown the ACTUAL invokation of the
                function.

                --
                Jeff "japhy" Pinyan japhy@... http://www.pobox.com/~japhy/
                RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
                ** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
                <stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
                [ I'm looking for programming work. If you like my work, let me know. ]
              • markveerman
                I figured it out! Although, I don t really understand the, but here s what it was: Below within the sub I originally had: my @fieldnames = $db- ...
                Message 7 of 12 , May 2, 2002
                • 0 Attachment
                  I figured it out! Although, I don't really understand the, but
                  here's what it was:

                  Below within the sub I originally had: my @fieldnames = $db-
                  >FieldNames(); return @fieldnames; When I removed the word "my",
                  @fieldnames was returned correctly. Also, I didn't realize you could
                  call the function like @array = function() - so that was helpful too.

                  thanks for your help japhy!
                  /mark

                  use Win32::ODBC;
                  my $dsn = "mysql";
                  my $table = "table";
                  my $sql = "SELECT doc_name FROM " . $table . " WHERE status = 'Q'";

                  odbc($dsn, $table, $sql);

                  foreach $fieldnames(@fieldnames){
                  print $fieldnames . "\n";
                  }

                  sub odbc {
                  my ($dsn, $table, $sql) = @_;
                  use Win32::ODBC;
                  my $db = new Win32::ODBC($dsn);

                  if (!$db){
                  die "Error connecting: " . Win32::ODBC::Error() . "\n";
                  }

                  if ($db->Sql($sql)) {
                  print "Error submitting SQL statement: " . $db->Error
                  () . "\n" . $sql;
                  }
                  else{
                  @fieldnames = $db->FieldNames();
                  return @fieldnames;
                  }

                  }



                  --- In perl-beginner@y..., Jeff 'japhy' Pinyan <japhy@p...> wrote:
                  > On May 2, markveerman said:
                  >
                  > >> You've shown the function, but not what you're doing with it.
                  > >
                  > >If I use the following within the sub routine:
                  > >
                  > ><snip>
                  > >my @fieldnames = $db->FieldNames();
                  > >foreach $fieldnames(@fieldnames){
                  > >print $fieldnames . "\n";
                  > ></snip>
                  > >
                  > >It works fine, so I know that $fieldnames is a working array, but
                  > >when I try to use return @fieldnames; and put the foreach loop
                  > >outside of the function I get nothing.
                  >
                  > You're returning the array, but what are you returning it TO?
                  >
                  > >Does it have something to do with the type of array or the format
                  of
                  > >the data in the array? I tried your sample and that worked fine.
                  Am
                  > >I missing something obvious?
                  >
                  > I think so. My code stores the return value of the function:
                  >
                  > @output = function();
                  >
                  > Does yours? You still haven't shown the ACTUAL invokation of the
                  > function.
                  >
                  > --
                  > Jeff "japhy" Pinyan japhy@p...
                  http://www.pobox.com/~japhy/
                  > RPI Acacia brother #734 http://www.perlmonks.org/
                  http://www.cpan.org/
                  > ** Look for "Regular Expressions in Perl" published by Manning, in
                  2002 **
                  > <stu> what does y/// stand for? <tenderpuss> why, yansliterate of
                  course.
                  > [ I'm looking for programming work. If you like my work, let me
                  know. ]
                • Jeff 'japhy' Pinyan
                  ... No! You re not returning anything then! You re just setting a global array. The concept of returning something from a function is that you ACTUALLY send
                  Message 8 of 12 , May 2, 2002
                  • 0 Attachment
                    On May 2, markveerman said:

                    >Below within the sub I originally had: my @fieldnames = $db-
                    >>FieldNames(); return @fieldnames; When I removed the word "my",
                    >@fieldnames was returned correctly. Also, I didn't realize you could
                    >call the function like @array = function() - so that was helpful too.

                    No! You're not returning anything then! You're just setting a global
                    array. The concept of returning something from a function is that you
                    ACTUALLY send content FROM the function BACK to the program. Also, your
                    approach of removing 'my' makes your code possibly less safe, since you
                    might end up ruining some OTHER @fieldnames array. Using my() helps keep
                    your variables scoped properly.

                    Compare:

                    sub sum {
                    $x = 0;
                    for (@_) { $x += $_ }
                    }

                    sub set_sum {
                    my $x = 0;
                    for (@_) { $x += $_ }
                    return $x;
                    }

                    sum(1,2,4,8);
                    my $n = set_sum(1,3,5,7);

                    The first function sets a global variable $x with the value 15; the second
                    stores the value 16 in $n. With the first method, you have no control
                    over WHERE the data goes -- the function does. With the second method,
                    YOU have control where the data.

                    > else{
                    > @fieldnames = $db->FieldNames();
                    > return @fieldnames;
                    > }

                    There's no point in returning @fieldnames. You're not returning it TO
                    anything.

                    --
                    Jeff "japhy" Pinyan japhy@... http://www.pobox.com/~japhy/
                    RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
                    ** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
                    <stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
                    [ I'm looking for programming work. If you like my work, let me know. ]
                  • markveerman
                    ... global ... you ... your ... you ... helps keep ... Okay, I think I understand what you re saying, however, If I don t return @fieldnames, then I can t do
                    Message 9 of 12 , May 2, 2002
                    • 0 Attachment
                      > No! You're not returning anything then! You're just setting a
                      global
                      > array. The concept of returning something from a function is that
                      you
                      > ACTUALLY send content FROM the function BACK to the program. Also,
                      your
                      > approach of removing 'my' makes your code possibly less safe, since
                      you
                      > might end up ruining some OTHER @fieldnames array. Using my()
                      helps keep
                      > your variables scoped properly.

                      Okay, I think I understand what you're saying, however, If I don't
                      return @fieldnames, then I can't do anything with them ... like print
                      them out. I'm going to be using this function to query a db and
                      return the results. I can't do anything with the results within the
                      function, because I want it to remain generic enough so I can use it
                      for all my db queries. So, in order for me to USE the info I get
                      from the queries, I've got to return the data BACK to the program.

                      > There's no point in returning @fieldnames. You're not returning it
                      TO anything.

                      I thought I was returning it to the program so I could then loop
                      through it and print out the field names. Bear with me, I'm really
                      trying to understand :-).
                      /mark

                      >
                      > --
                      > Jeff "japhy" Pinyan japhy@p...
                      http://www.pobox.com/~japhy/
                      > RPI Acacia brother #734 http://www.perlmonks.org/
                      http://www.cpan.org/
                      > ** Look for "Regular Expressions in Perl" published by Manning, in
                      2002 **
                      > <stu> what does y/// stand for? <tenderpuss> why, yansliterate of
                      course.
                      > [ I'm looking for programming work. If you like my work, let me
                      know. ]
                    • markveerman
                      Thanks Charles - Are you telling me that even though it works it s not good code? :-). As if it s not totally obvious - I m a novice. /mark ... In defense of
                      Message 10 of 12 , May 2, 2002
                      • 0 Attachment
                        Thanks Charles - Are you telling me that even though it works it's
                        not good code? :-). As if it's not totally obvious - I'm a novice.
                        /mark

                        > So this is what Japhy meant. Shame on you Japhy, I
                        > can't believe you'd let Mark do it this way. :)

                        In defense of Japhy, today was the first day I've ever written a sub
                        routine, so the issues with scoping and local/global variables is
                        entirely new.

                        Thanks to you both for the assistance.
                        /mark
                      • Jeff 'japhy' Pinyan
                        ... Gaaah! No, Mark misunderstood my code, Charles. Mark, the return() function does not tell Perl that variables you used in your function can be used
                        Message 11 of 12 , May 2, 2002
                        • 0 Attachment
                          On May 2, Charles K. Clarkson said:

                          >"markveerman" <mark@...> wrote:
                          >
                          >: I figured it out! Although, I don't really understand the, but
                          >: here's what it was:
                          >:
                          >: Below within the sub I originally had: my @fieldnames = $db-
                          >: >FieldNames(); return @fieldnames; When I removed the word "my",
                          >: @fieldnames was returned correctly. Also, I didn't realize you could
                          >: call the function like @array = function() - so that was helpful too.
                          >:
                          >: thanks for your help japhy!
                          >
                          > So this is what Japhy meant. Shame on you Japhy, I
                          >can't believe you'd let Mark do it this way. :)

                          Gaaah! No, Mark misunderstood my code, Charles.

                          Mark, the return() function does not tell Perl that variables you used in
                          your function can be used OUTSIDE the function. It does nothing of the
                          sort. All it does is tell Perl that it can put the VALUES of those
                          variables in place you can get them from; specifically, from the return
                          value of the function:

                          sub cube {
                          my $n = shift;
                          return $n ** 3;
                          }

                          $big = cube(1234);

                          The function cube() RETURNS ONE VALUE. If you don't use the return value
                          somehow (like storing it in a variable, or printing it) then it
                          disappears.

                          Here are some examples to see if it becomes clear to you.

                          sub foobar {
                          my @bah = (1, 2, 3, 4);
                          return @bah;
                          }

                          my @bah = (5, 6);
                          foobar();
                          print "@bah\n"; # 5 6

                          ###########################

                          sub foobar {
                          my @bah = (1, 2, 3, 4);
                          }

                          my @bah = (5, 6);
                          foobar();
                          print "@bah\n"; # 5 6

                          ###########################

                          sub foobar {
                          my @bah = (1, 2, 3, 4);
                          return @bah;
                          }

                          my @bah = (5, 6);
                          @bah = foobar();
                          print "@bah\n"; # 1 2 3 4

                          ###########################

                          sub foobar {
                          my @bah = (1, 2, 3, 4);
                          }

                          my @bah = (5, 6);
                          @bah = foobar(); # foobar() returns the last thing evaluated, @bah
                          print "@bah\n"; # 1 2 3 4 (but only because you're lucky!)

                          ###########################

                          sub foobar {
                          @bah = (1, 2, 3, 4); # THIS SETS THE OUTSIDE @bah (bad idea)
                          return @bah;
                          }

                          my @bah = (5, 6);
                          foobar();
                          print "@bah\n"; # 1 2 3 4

                          ###########################

                          sub foobar {
                          my @bah = (1, 2, 3, 4); # DITTO
                          }

                          my @bah = (5, 6);
                          foobar();
                          print "@bah\n"; # 5 6

                          --
                          Jeff "japhy" Pinyan japhy@... http://www.pobox.com/~japhy/
                          RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
                          ** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
                          <stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
                          [ I'm looking for programming work. If you like my work, let me know. ]
                        • Franki
                          well you just taught me something as well.. I hadn t really given it much thought, but now that I have, its kinda obvious and I am ashamed of myself for not
                          Message 12 of 12 , May 3, 2002
                          • 0 Attachment
                            well you just taught me something as well..

                            I hadn't really given it much thought, but now that I have, its kinda
                            obvious and I am ashamed of myself for not realising it..

                            I had been wondering why not all of my "return" code works...

                            Thankyou..


                            regards

                            Frank

                            -----Original Message-----
                            From: Jeff 'japhy' Pinyan [mailto:japhy@...]
                            Sent: Friday, 3 May 2002 10:16 AM
                            To: perl-beginner@yahoogroups.com
                            Subject: Re: [PBML] returning arrays and hashes from a subroutine


                            On May 2, Charles K. Clarkson said:

                            >"markveerman" <mark@...> wrote:
                            >
                            >: I figured it out! Although, I don't really understand the, but
                            >: here's what it was:
                            >:
                            >: Below within the sub I originally had: my @fieldnames = $db-
                            >: >FieldNames(); return @fieldnames; When I removed the word "my",
                            >: @fieldnames was returned correctly. Also, I didn't realize you could
                            >: call the function like @array = function() - so that was helpful too.
                            >:
                            >: thanks for your help japhy!
                            >
                            > So this is what Japhy meant. Shame on you Japhy, I
                            >can't believe you'd let Mark do it this way. :)

                            Gaaah! No, Mark misunderstood my code, Charles.

                            Mark, the return() function does not tell Perl that variables you used in
                            your function can be used OUTSIDE the function. It does nothing of the
                            sort. All it does is tell Perl that it can put the VALUES of those
                            variables in place you can get them from; specifically, from the return
                            value of the function:

                            sub cube {
                            my $n = shift;
                            return $n ** 3;
                            }

                            $big = cube(1234);

                            The function cube() RETURNS ONE VALUE. If you don't use the return value
                            somehow (like storing it in a variable, or printing it) then it
                            disappears.

                            Here are some examples to see if it becomes clear to you.

                            sub foobar {
                            my @bah = (1, 2, 3, 4);
                            return @bah;
                            }

                            my @bah = (5, 6);
                            foobar();
                            print "@bah\n"; # 5 6

                            ###########################

                            sub foobar {
                            my @bah = (1, 2, 3, 4);
                            }

                            my @bah = (5, 6);
                            foobar();
                            print "@bah\n"; # 5 6

                            ###########################

                            sub foobar {
                            my @bah = (1, 2, 3, 4);
                            return @bah;
                            }

                            my @bah = (5, 6);
                            @bah = foobar();
                            print "@bah\n"; # 1 2 3 4

                            ###########################

                            sub foobar {
                            my @bah = (1, 2, 3, 4);
                            }

                            my @bah = (5, 6);
                            @bah = foobar(); # foobar() returns the last thing evaluated, @bah
                            print "@bah\n"; # 1 2 3 4 (but only because you're lucky!)

                            ###########################

                            sub foobar {
                            @bah = (1, 2, 3, 4); # THIS SETS THE OUTSIDE @bah (bad idea)
                            return @bah;
                            }

                            my @bah = (5, 6);
                            foobar();
                            print "@bah\n"; # 1 2 3 4

                            ###########################

                            sub foobar {
                            my @bah = (1, 2, 3, 4); # DITTO
                            }

                            my @bah = (5, 6);
                            foobar();
                            print "@bah\n"; # 5 6

                            --
                            Jeff "japhy" Pinyan japhy@... http://www.pobox.com/~japhy/
                            RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
                            ** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
                            <stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
                            [ I'm looking for programming work. If you like my work, let me know. ]



                            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/
                          Your message has been successfully submitted and would be delivered to recipients shortly.