Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

what is the return value

by arasumg (Initiate)
on Jul 09, 2013 at 04:02 UTC ( [id://1043232]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, Can some one help me line by line?

sub firstline { open( my $in, shift ) && return scalar <$in>; # no close() required }

Replies are listed 'Best First'.
Re: what is the return value
by davido (Cardinal) on Jul 09, 2013 at 05:20 UTC

    If the open is successful it will return the first line in the file that was passed as a parameter when the function was called. If the open is unsuccessful, the logical short circuit stops at the open, and returns what it returned upon failure, which is undef.

    It's important to observe that one must test explicitly whether the return value is "defined". In an error condition, it will not be. Testing the return value for truth/falsehood isn't sufficient, since the first line of a file could be a value that Perl considers false.

    Update: I had kinda lost track of this thread, not realizing that there had been additional discussion. But Skeeve correctly pointed out to me that his explanation in Re: what is the return value is accurate, and mine isn't. The flaw in my analysis is that the my $in variable will not have been instantiated. My analysis would have been accurate had $in been pre-declared ahead of the open, but it wasn't, and Skeeve's analysis is spot on.


    Dave

Re: what is the return value
by NetWallah (Canon) on Jul 09, 2013 at 04:30 UTC
    I depends on whether or not the "open" is successful.

    Why don't you try running the code to find out ?

    Each function you use is documented in 'perldoc -f <name>', so you can research what the lines do, and ask specific questions about things you need clarification on.

                 My goal ... to kill off the slow brain cells that are holding me back from synergizing my knowledge of vertically integrated mobile platforms in local cloud-based content management system datafication.

Re: what is the return value
by The_Dj (Beadle) on Jul 09, 2013 at 04:45 UTC
    Firstly, it's broken. The # marks a comment, so the closing } will be ignored and break the code. Looking at:
    1 sub firstline { 2 open( my $in, shift ) 3 && return 4 scalar <$in>; 5 # no close() required 6 }
    line 1: starting a new sub called 'firstline'
    Line 2: (from right to left)
        shift: gets the first parameter passed to the sub
        $in: is just a variable
        my $in: says $in only exists in this sub
        open: open a file. In this case the file name is the first parameter to the sub, and $in becomes the handle
    line 3: &&: A logical-and ensure that if the file open fails, the next command will be skipped.
        return: return the following data
    line 4: scalar: tells perl to think of the next 'thing' as a single line of text.
        <$in>: read from the file handle. Combined with the 'scalar' instruction will get just one line.
    line 5: a comment noting that the file is automatically closed when the $in filehandle 'dissapears' at the end of the sub.
    line 6: ending the sub.

    So.. Line 2 opens a file. Line 4 gets a single line of text and Line 3 returns that single line.

    Try reading http://perldoc.perl.org/perlopentut.html and other tutorials.
Re: what is the return value
by Skeeve (Parson) on Jul 09, 2013 at 14:08 UTC

    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

      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

      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
      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!

Re: what is the return value
by Skeeve (Parson) on Jul 09, 2013 at 13:49 UTC

    That code won't work.

    Put "use strict; use warnings;" in

    use strict; use warnings; sub firstline { open (my $in, shift) && return scalar <$in>; # no close() required } print firstline("/etc/hosts");
    and you'll get:
    Global symbol "$in" requires explicit package name at firstline.pl lin +e 4. Execution of firstline.pl aborted due to compilation errors.
    If you don't use strict/warnings, you'll simply get an empty line.

    Update: Removed the "; 1 " which I putted in to make the code at least print out something.

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
      Works for me.
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        Maybe different perl version?
        $ perl -v This is perl 5, version 14, subversion 2 (v5.14.2) built for cygwin-th +read-multi-64int (with 7 registered patches, see perl -V for more detail) Copyright 1987-2011, Larry Wall Perl may be copied only under the terms of either the Artistic License + or the GNU General Public License, which may be found in the Perl 5 source ki +t. Complete documentation for Perl, including FAQ lists, should be found +on this system using "man perl" or "perldoc perl". If you have access to + the Internet, point your browser at http://www.perl.org/, the Perl Home Pa +ge.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1043232]
Approved by hdb
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-03-29 10:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found