I think you are asking a general question about passing arrays into subroutines and have confused people with the lengthy example you have provided...

It looks like @data_one is a private variable in the words() subroutine. You also attempt to use it in the print_search_results() subroutine. Maybe you are trying to use it as a global array and are shadowing it in your words() sub?

You might try removing the my @data_one; declaration in the words() sub. Better would be to actually pass it in. There are two ways to do that. You can pass it in directly or by reference. By reference is better.

Perl subs get their arguments in the @_ array. Here's how to pass an array by reference:

sub mysub { my @array = @$_[0]; # Makes a copy. Not efficient. print $array[0], "\n"; } my @a = (1 .. 10); mysub(\@a); # \@a is a reference to the array @a.
In the interest of keeping the example simple, that makes a copy of the data which isn't particularly efficient. You can avoid references entirely but doing so isn't very efficient either and it doesn't work very well if you have to pass in more than one array.
mysub { my @array = @_; # Copying again. Not efficient. print $array[0], "\n"; } my @a = (1 .. 10); mysub(@a); # Send the array as @_
My suggestion is to learn how to use references right away. You can start with some of the Tutorials right here like references and References quick reference. Ideally, your code would look more like this:
mysub { my ($arrayref) = @_; print $arrayref->[0], "\n"; } my @a = (1 .. 10); mysub( \@a );

-sauoq
"My two cents aren't worth a dime.";

In reply to Re: passing an array to a subroutine by sauoq
in thread passing an array to a subroutine by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.