robertw has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perlmonks I imported html which i want to parse but when i pass it into a subroutine as a scalar i can only get the input in an array, When i pass the string into the sub and then set it to an array change that array back to the original string scalar value? Sorry guys I really have no idea how to handle this, and I can give some of my test scripts for clarity:S thank you so much

my $html = "hello"; routine($html); sub routine { print $_; print " "; print @_; }

Replies are listed 'Best First'.
Re: subroutine scalar string input
by BrowserUk (Patriarch) on Oct 20, 2012 at 23:44 UTC

    When you pass arguments to a subroutine, they are passed in via the special array @_. To get them back into named scalars, assign that to the name(s) you want:

    my $html = "hello"; routine( $html ); sub routine{ my( $arg1 ) = @_; print $arg1; }

    NOTE: the variable name $arg1 is just an example.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    RIP Neil Armstrong

Re: subroutine scalar string input
by 2teez (Vicar) on Oct 20, 2012 at 23:51 UTC

    Hi robertw,

    First of all, what you passed to the subroutrine is a scalar variable named $html not an html doc or html tag related string.
    perlsub documentation, then gives a clear explanation of parameters passed to a subroutine as thus:

    "The Perl model for function call and return values is simple: all functions are passed as parameters one single flat list of scalars, and all functions likewise return to their caller one single flat list of scalars. Any arrays or hashes in these call and return lists will collapse, losing their identities--but you may always use pass-by-reference instead to avoid this..."

    So, within a subroutine the array @_ contains the parameters passed to that subroutine.
    Thus this;

    my $html = "hello"; routine($html); routine2($html); sub routine { my $greetings = shift @_; print $greetings; ## print hello } #OR sub routine2 { my ($greetings) = @_; print $greetings; ## print hello }
    In case however, you intended to parse your imported html,
    you may consider using an html parser module like HTML::TokeParser or HTML::TreeBuilder.
    Hope this helps.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
      thank you so much all of you this is very helpful:)
Re: subroutine scalar string input
by ikegami (Patriarch) on Oct 20, 2012 at 23:19 UTC
    You seem to have problems communicating in English. Perhaps you could show us what you want to do?