in reply to Re^2: perl to run awk and sed
in thread perl to run awk and sed

My code above pretty well does this without shelling out:

use warnings; use strict; my @lines = ( "myserver.it.ca. XXXX XXX XXX XXXXXXXXXXX", "myserver.it.org. XXXX XXX XXX XXXXXXXXXXX", "myserver.it.com. XXXX XXX XXX XXXXXXXXXXX", ); for my $line (@lines){ my $server = (split /\s+/, $line)[0]; $server =~ s/\.$//; print "$server\n"; } __END__ myserver.it.ca myserver.it.org myserver.it.com

Replies are listed 'Best First'.
Re^4: perl to run awk and sed
by GotToBTru (Prior) on Dec 01, 2015 at 15:26 UTC

    Since interest is limited to the very first returned value, we can limit the split and save a little time.

    my $server - (split /\s+/, $line, 2)[0];

    The optional third parameter limits the number of returned values to 2, so perl doesn't waste time splitting the rest of the line.

    Dum Spiro Spero
Re^4: perl to run awk and sed
by deelinux (Novice) on Nov 30, 2015 at 20:15 UTC

    many thanks, time to digest and play

      I will try to explain in detail. When I post on PerlMonks, I try to be a bit more verbose than when I'm writing my own code, but I also try to show brief shortcuts...

      # don't leave home without these ;) use warnings; use strict; # this could be from a file or whatever my @lines = ( "myserver.it.ca. XXXX XXX XXX XXXXXXXXXXX", "myserver.it.org. XXXX XXX XXX XXXXXXXXXXX", "myserver.it.com. XXXX XXX XXX XXXXXXXXXXX", ); # in the next line, we take every array element of the above @lines, # and work on them one at a time. $line contains each # of the array elements, in order for my $line (@lines){ # the below split() is a bit of trickery. we split the line on # whitespace (\s) (the + is superfluous in this case, it means # "one or more" (you had a tab), so we split on ANY whitespace). # # because I wrapped the split() within parens (()), that forces # it into list context, so I treat it as an array (of sorts), # and after the split() executes, I can immediately take # the first element of it ([0]), and assign it to $server. # # that isn't anything special... it's just avoiding splitting # into a named array, then having to take the first element # from that and putting it into the variable... two-stage example: # # my @servers = split /\s/, $line; # my $server = $servers[0]; my $server = (split /\s+/, $line)[0]; # the following does a substitution... it replaces a '.' # (dot, period) character at the very end of $server with nothing # (ie. it removes it) in your OP, you had s/.$//. In Perl # (and in sed), a '.' represents *any* character (perl doesn't # recognize a '.' as a newline by default, I don't know about sed) # I changed it so it looks for a dot explicitly by escaping it # with a backslash (\). After the substitution, we print... $server =~ s/\.$//; print "$server\n"; }