Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: what is the return value

by Skeeve (Vicar)
on Jul 09, 2013 at 14:08 UTC ( #1043323=note: print w/ replies, xml ) Need Help??


in reply to what is the return value

To proove that the code does not do what's stated here, try this:

  1. Create a file "a" containing the line "from a"
  2. Create a file "b" containing the line "from b"
  3. Change the code to this:
    use strict; use warnings; open my $in, '<', "a"; print firstline("b"); sub firstline { open (my $in, shift) && return scalar <$in>; # no close() required }

If the descriptions here were right, you should get "from b" but you will get "from a".

The reason is that "<$in>" is referring to the outer $in.


s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e


Comment on Re: what is the return value
Select or Download Code
Re^2: what is the return value
by fishmonger (Pilgrim) on Jul 09, 2013 at 14:42 UTC

    You are correct, and there are several ways the OP could fix that problem. The first thing that I thought of would be to simply declare $in prior to the open call. The second was to use the ternary operator.

    return open ($in, '<', shift ) ? scalar <$in> : undef; # using undef may or may not be desirable in this case
Re^2: what is the return value
by MidLifeXis (Prior) on Jul 09, 2013 at 14:42 UTC

    And this works 'as expected', I think...

    use strict; use warnings; open my $in, '<', "a"; print firstline("b"); sub firstline { my $retval = open (my $in, shift); $retval && return scalar <$in>; # no close() required }

    --MidLifeXis

Re^2: what is the return value
by ww (Bishop) on Jul 09, 2013 at 15:14 UTC
    Whereas, and TIMTOWTDI:
    #!/usr/bin/perl use strict; use warnings; use 5.016; # Modified from parent and MidLifeXis' 1043331 open my $in, '<', "a.txt"; print firstline("b.txt"); sub firstline { say "at_: @_"; my $file = shift; my $retval = open (my $FH, '<', $file ); $retval && return scalar <$FH>; # no close() required }
    prints:
    at_: b.txt from b

    If you didn't program your executable by toggling in binary, it wasn't really programming!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2014-08-29 10:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (277 votes), past polls