Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

How do I remove newline character from a number got from unix command

by tousifp (Novice)
on Sep 04, 2013 at 12:12 UTC ( [id://1052309]=perlquestion: print w/replies, xml ) Need Help??

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

Trouble again. I run following thing and why the heel is newline character attached to $year? How can I remove it?

$year=`date +%Y`; printf "$year";

Thank You all Guys for your Kinda Help!

Replies are listed 'Best First'.
Re: How do I remove newline character from a number got from unix command
by choroba (Cardinal) on Sep 04, 2013 at 12:13 UTC
    As to why: because date appends it to its output.

    As to how: chomp

    Update: As to TIMTOWTDI and portability: localtime

    1900 + (localtime)[5]
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: How do I remove newline character from a number got from unix command
by space_monk (Chaplain) on Sep 04, 2013 at 12:34 UTC
    The newline is attached because you're executing an OS command to do the work. Try using something more operating system agnostic - e.g.
    use POSIX qw(strftime); my $date = strftime "%Y", localtime; print $date;
    or...
    use DateTime qw(); DateTime->now->strftime('%Y');
    If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)
Re: How do I remove newline character from a number got from unix command
by Tux (Canon) on Sep 04, 2013 at 12:19 UTC
    1. As the others already said: use chomp
    2. Why use external commands when all is avail in perl?
      my $year = 1900 + (localtime)[5];
    3. Why quote $year in the print? print $year; will do just what you want. There is no need for forced stringification.
    4. Why printf? You are not using any formatting at all.

    Enjoy, Have FUN! H.Merijn

      How can I have date and month in a similar fashion? I need like this : 2013-09-04 and "Sep 04"

        my $date_as_YYYY_MM_DD = do { my @d = localtime; sprintf "%04d-%02d-%02d", $d[5] + 1900, ++$d[4], $d[3]; };

        but that is most likely better done with POSIX' strftime:

        use POSIX qw( strftime ); my $d_YMD = POSIX::strftime ("%Y-%m-%d", localtime); my $d_Md = POSIX::strftime ("%d %b", localtime); # I prefer 04 Sep ov +er Sep 04

        Enjoy, Have FUN! H.Merijn
Re: How do I remove newline character from a number got from unix command
by marinersk (Priest) on Sep 04, 2013 at 12:14 UTC
    Updated: (Added notes, original solution the same)
    Updated: (Expanded solution due to peer pressure) :-)

    Don't have a Linux system up but presume chomp would do it:

    $year=`date +%Y`; chomp $year; printf "$year";

    I see choroba was faster on the post than I was, and also gave a more complete answer.

    Okay, fine, I'll give in. Everyone is mentioning localtime, but my old eyes don't see the commensurate adjustment warning:

    # Humanize the time my $nowsse = time; my ($nowsec,$nowmin,$nowhou,$nowdom,$nowmon,$nowyea,$nowdow,$nowdo +y,$nowdst) = localtime($nowsse); $nowyea += 1900; $nowmon++;

    With some further explanations of my TLAs:

    • $nowsse: Seconds since Epoch
    • $nowdom: Day of Month
    • $nowdow: Day of Week
    • $nowdoy: Day of Year
    • $nowdst: Daylight Savings Time in effect?

    Some additional thoughts:

    • Any time you shell out to run an OS command you should really examine what you get back. Each OS behaves a little bit differently and you'll want to get a feel for what you get back. You may need to massage it for storage or modification (such as chomping off the newline in your example).
    • Use of Perl native features is going to be more portable than a homespun OS interface; while not always the right answer, in my opinion based on a few decades of experience this should be a consideration -- even for one-off work which might later be used as a template for something less one-off-ish.
    • Use of a published module (a la CPAN, etc.) is likely to be more portable than an OS-specific hack, but as always caveat emptor, so test its functionality and results before releasing it into the wild.

    The original question was specifically about the newline on the OS response, so that's what my post covered. It was irresponsible of me to not mention, as so many other Monks have, the particular function you appeared to be attempting to perform was available via both native and module functionality.

    But the other Monks did cover that, rather thoroughly. I love Perlmonks. :-)

      I was using chomp($year) and so not returning expected result. Thanks

        I was using chomp($year) and so not returning expected result. Thanks

        So...

        The documentation for chomp tells you how chomp works and what it returns.
        It is the contents of the variable itself that you should verify.

        Update: to be concise, I added "the contents of" to the line above.

        Cheers, Sören

        Créateur des bugs mobiles - let loose once, run everywhere.
        (hooked on the Perl Programming language)

Log In?
Username:
Password:

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

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

    No recent polls found