Re: perl head and tail command ?



Rob Dixon wrote:
Richard Lee wrote:
I would imagine linux's head command can be replaced w/ chop
I asked this because I have a filehandle which was,

open $source, '/tmp/server.txt' ( and no doing head -1 /tmp/server.txt is not an option since I need to go through some other stuff
before i need to issue below command )

and I wanted to do

my $top = `head -1 $source`
my $bottom = `tail -1 $source`

but I realized I cannot do $source in back tick.

so I imagine i can do

my $top = chop $source;

But what about the $bottom one?

The chop() function simply removes the last character from a string and returns it. Since $source isn't a string you would get an error. Your best bet is likely to be the Tie::File module. For instance

use strict;
use warnings;

use Tie::File;

tie my @file, 'Tie::File', '/tmp/server.txt' or die $!;

my ($top, $bottom) = @file[0, -1];

HTH,

Rob


when you are doing it to filehandle vs array, which consumes more memory?

my source file is about 100,000 lines...

open my $source, 'tmp/server.txt' or die !$;

VS
tie my @file, 'Tie::File', '/tmp/server.txt' or die $!;


.



Relevant Pages

  • Re: match and grab
    ... Rob Dixon wrote: ... then Perl looks at this as a method call on $1 as an IO::Handle ... FILEHANDLE may be a scalar variable name, ... syntax works and does the same thing. ...
    (perl.beginners)
  • Re: perl head and tail command ?
    ... Rob Dixon wrote: ... my source file is about 100,000 lines... ... open my $source, 'tmp/server.txt' or die!$; ... Neither of them use any significant memory until you start reading from the file. ...
    (perl.beginners)
  • Re: perl head and tail command ?
    ... I asked this because I have a filehandle which was, ... my source file is about 100,000 lines... ... you should not worry about speed or memory usage until you have written the clearest program you can and then find that it consumes too many resources. ...
    (perl.beginners)
  • Re: Other ways to assign a filehandle to a variable?
    ... open(FILE, $filename) or die "whatever"; ... Using an undefined lexical in place of the filehandle automatically ... The lexicals are subject to strict ...
    (perl.beginners)
  • Re: Other ways to assign a filehandle to a variable?
    ... assign a filehandle to a scalar by doing something like: ... open(FILE, $filename) or die "whatever"; ... read from a filehandle into a scalar. ...
    (perl.beginners)