Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^2: Return Value from sub

by Dr Manhattan (Beadle)
on Sep 06, 2013 at 10:10 UTC ( #1052686=note: print w/ replies, xml ) Need Help??


in reply to Re: Return Value from sub
in thread Return Value from sub

I'm not using grep

my ($name) = seekName($id) print "$name\n"; sub seekName { my ($id) = $_[0]; open (IN, "<:utf8", "names.txt") or die "Can't open: $!"; seek In, $id, 0; my $line = <In>; return $line; }

Output just gives a bunch of 1's


Comment on Re^2: Return Value from sub
Download Code
Re^3: Return Value from sub
by Laurent_R (Prior) on Sep 06, 2013 at 10:16 UTC

    Context problem. Change the relevant line to:

    my $name = seekName($id);

    Alternate solution: return an array from your subroutine:

    return ($line); Update: added the second alternate solution.
Re^3: Return Value from sub
by Corion (Pope) on Sep 06, 2013 at 10:20 UTC

    When I try to run the code you posted, I only get these errors:

    C:\>perl -w tmp.pl Name "main::IN" used only once: possible typo at tmp.pl line 8. Use of uninitialized value $id in seek at tmp.pl line 10. seek() on unopened filehandle In at tmp.pl line 10. readline() on unopened filehandle In at tmp.pl line 11. Use of uninitialized value $name in concatenation (.) or string at tmp +.pl line 3.

    Please try to make sure that the code you post actually exhibits the problem you are trying to diagnose.

    When I change your code to the following:

    my $id= shift; my ($name) = seekName($id); print "$name\n"; sub seekName { my ($id) = $_[0]; open (IN, "<:utf8", $0) or die "Can't open: $!"; seek IN, $id, 0; my $line = <IN>; return $line; }

    ... it assigns $name a value depending on what number I give on the command line. So I would assume that this works and does not exhibit the problem of always printing 1.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1052686]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2015-07-03 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (47 votes), past polls