perl regex - convert multiple decimal numbers on a line to nearest integer











up vote
1
down vote

favorite
1












I am practicing a Perl regex question where I have lines in the following format that are read in from stdin:



I bought 2.3kg of oranges for $13.50.



It takes 4.5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



And I have to convert all the decimal numbers in each line to their nearest integer. So the expected output would look like:



I bought 2kg of oranges for $14.00.



It takes 5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



I have the following code:



#!/usr/bin/perl -w
use strict;
use warnings;
use Math::Round;

my @lines = <STDIN>;
chomp @lines;

foreach my $line (@lines) {
$line =~ s/(d+.?d*)/hello/g;
}


The part which I am not sure how to do is actually replace the decimal numbers in each line with their integer version. My approach is to read all the lines from stdin into an array, and then for each match on each line substitute the decimal number with its nearest whole number. I know you can round floating point numbers in Perl using the round() function.



However, using the round() function as the replacement text within the 's/(d+.?d*)//g' would not work. Using the substitution operator seemed to be the simplest approach, but I don't think I will be able to use it.
I am not exactly sure what other methods I could use to solve this problem. Any insights would be really appreciated.










share|improve this question


















  • 1




    You say "integer" but give $14.00 example? If you really mean to round prices to 0 cents you need to modify @ikegami solution, perhaps by adding an optional dollar match ($?) and then in the replacement have two cases, s/../$1 ? to-zero-cents : to-int/ge.
    – zdim
    Nov 10 at 8:13






  • 1




    A clumsy way to do the "zero-cents" above is to nest sprintf's, one for rounding the other for precision: s/($?)(d+.d+)/$1 ? $1.sprintf("%.2f",sprintf "%.0f", $2) : sprintf("%.0f",$2)/ge. There are other ways.
    – zdim
    Nov 10 at 8:14

















up vote
1
down vote

favorite
1












I am practicing a Perl regex question where I have lines in the following format that are read in from stdin:



I bought 2.3kg of oranges for $13.50.



It takes 4.5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



And I have to convert all the decimal numbers in each line to their nearest integer. So the expected output would look like:



I bought 2kg of oranges for $14.00.



It takes 5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



I have the following code:



#!/usr/bin/perl -w
use strict;
use warnings;
use Math::Round;

my @lines = <STDIN>;
chomp @lines;

foreach my $line (@lines) {
$line =~ s/(d+.?d*)/hello/g;
}


The part which I am not sure how to do is actually replace the decimal numbers in each line with their integer version. My approach is to read all the lines from stdin into an array, and then for each match on each line substitute the decimal number with its nearest whole number. I know you can round floating point numbers in Perl using the round() function.



However, using the round() function as the replacement text within the 's/(d+.?d*)//g' would not work. Using the substitution operator seemed to be the simplest approach, but I don't think I will be able to use it.
I am not exactly sure what other methods I could use to solve this problem. Any insights would be really appreciated.










share|improve this question


















  • 1




    You say "integer" but give $14.00 example? If you really mean to round prices to 0 cents you need to modify @ikegami solution, perhaps by adding an optional dollar match ($?) and then in the replacement have two cases, s/../$1 ? to-zero-cents : to-int/ge.
    – zdim
    Nov 10 at 8:13






  • 1




    A clumsy way to do the "zero-cents" above is to nest sprintf's, one for rounding the other for precision: s/($?)(d+.d+)/$1 ? $1.sprintf("%.2f",sprintf "%.0f", $2) : sprintf("%.0f",$2)/ge. There are other ways.
    – zdim
    Nov 10 at 8:14















up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1





I am practicing a Perl regex question where I have lines in the following format that are read in from stdin:



I bought 2.3kg of oranges for $13.50.



It takes 4.5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



And I have to convert all the decimal numbers in each line to their nearest integer. So the expected output would look like:



I bought 2kg of oranges for $14.00.



It takes 5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



I have the following code:



#!/usr/bin/perl -w
use strict;
use warnings;
use Math::Round;

my @lines = <STDIN>;
chomp @lines;

foreach my $line (@lines) {
$line =~ s/(d+.?d*)/hello/g;
}


The part which I am not sure how to do is actually replace the decimal numbers in each line with their integer version. My approach is to read all the lines from stdin into an array, and then for each match on each line substitute the decimal number with its nearest whole number. I know you can round floating point numbers in Perl using the round() function.



However, using the round() function as the replacement text within the 's/(d+.?d*)//g' would not work. Using the substitution operator seemed to be the simplest approach, but I don't think I will be able to use it.
I am not exactly sure what other methods I could use to solve this problem. Any insights would be really appreciated.










share|improve this question













I am practicing a Perl regex question where I have lines in the following format that are read in from stdin:



I bought 2.3kg of oranges for $13.50.



It takes 4.5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



And I have to convert all the decimal numbers in each line to their nearest integer. So the expected output would look like:



I bought 2kg of oranges for $14.00.



It takes 5 hours to get from the city to the sea.



She moved in 2010, and left in 2014.



I have the following code:



#!/usr/bin/perl -w
use strict;
use warnings;
use Math::Round;

my @lines = <STDIN>;
chomp @lines;

foreach my $line (@lines) {
$line =~ s/(d+.?d*)/hello/g;
}


The part which I am not sure how to do is actually replace the decimal numbers in each line with their integer version. My approach is to read all the lines from stdin into an array, and then for each match on each line substitute the decimal number with its nearest whole number. I know you can round floating point numbers in Perl using the round() function.



However, using the round() function as the replacement text within the 's/(d+.?d*)//g' would not work. Using the substitution operator seemed to be the simplest approach, but I don't think I will be able to use it.
I am not exactly sure what other methods I could use to solve this problem. Any insights would be really appreciated.







regex perl






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 5:20









ceno980

805




805








  • 1




    You say "integer" but give $14.00 example? If you really mean to round prices to 0 cents you need to modify @ikegami solution, perhaps by adding an optional dollar match ($?) and then in the replacement have two cases, s/../$1 ? to-zero-cents : to-int/ge.
    – zdim
    Nov 10 at 8:13






  • 1




    A clumsy way to do the "zero-cents" above is to nest sprintf's, one for rounding the other for precision: s/($?)(d+.d+)/$1 ? $1.sprintf("%.2f",sprintf "%.0f", $2) : sprintf("%.0f",$2)/ge. There are other ways.
    – zdim
    Nov 10 at 8:14
















  • 1




    You say "integer" but give $14.00 example? If you really mean to round prices to 0 cents you need to modify @ikegami solution, perhaps by adding an optional dollar match ($?) and then in the replacement have two cases, s/../$1 ? to-zero-cents : to-int/ge.
    – zdim
    Nov 10 at 8:13






  • 1




    A clumsy way to do the "zero-cents" above is to nest sprintf's, one for rounding the other for precision: s/($?)(d+.d+)/$1 ? $1.sprintf("%.2f",sprintf "%.0f", $2) : sprintf("%.0f",$2)/ge. There are other ways.
    – zdim
    Nov 10 at 8:14










1




1




You say "integer" but give $14.00 example? If you really mean to round prices to 0 cents you need to modify @ikegami solution, perhaps by adding an optional dollar match ($?) and then in the replacement have two cases, s/../$1 ? to-zero-cents : to-int/ge.
– zdim
Nov 10 at 8:13




You say "integer" but give $14.00 example? If you really mean to round prices to 0 cents you need to modify @ikegami solution, perhaps by adding an optional dollar match ($?) and then in the replacement have two cases, s/../$1 ? to-zero-cents : to-int/ge.
– zdim
Nov 10 at 8:13




1




1




A clumsy way to do the "zero-cents" above is to nest sprintf's, one for rounding the other for precision: s/($?)(d+.d+)/$1 ? $1.sprintf("%.2f",sprintf "%.0f", $2) : sprintf("%.0f",$2)/ge. There are other ways.
– zdim
Nov 10 at 8:14






A clumsy way to do the "zero-cents" above is to nest sprintf's, one for rounding the other for precision: s/($?)(d+.d+)/$1 ? $1.sprintf("%.2f",sprintf "%.0f", $2) : sprintf("%.0f",$2)/ge. There are other ways.
– zdim
Nov 10 at 8:14














1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










Use s///e to put code as the replacement expression. The code is expected to return the value to use as the replacement.



 s/(d+.d+)/ sprintf("%.0f", $1) /eg


(Feel free to use Math::Round's round if you wish. I just used that with which I am familiar.)






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236211%2fperl-regex-convert-multiple-decimal-numbers-on-a-line-to-nearest-integer%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote



    accepted










    Use s///e to put code as the replacement expression. The code is expected to return the value to use as the replacement.



     s/(d+.d+)/ sprintf("%.0f", $1) /eg


    (Feel free to use Math::Round's round if you wish. I just used that with which I am familiar.)






    share|improve this answer

























      up vote
      2
      down vote



      accepted










      Use s///e to put code as the replacement expression. The code is expected to return the value to use as the replacement.



       s/(d+.d+)/ sprintf("%.0f", $1) /eg


      (Feel free to use Math::Round's round if you wish. I just used that with which I am familiar.)






      share|improve this answer























        up vote
        2
        down vote



        accepted







        up vote
        2
        down vote



        accepted






        Use s///e to put code as the replacement expression. The code is expected to return the value to use as the replacement.



         s/(d+.d+)/ sprintf("%.0f", $1) /eg


        (Feel free to use Math::Round's round if you wish. I just used that with which I am familiar.)






        share|improve this answer












        Use s///e to put code as the replacement expression. The code is expected to return the value to use as the replacement.



         s/(d+.d+)/ sprintf("%.0f", $1) /eg


        (Feel free to use Math::Round's round if you wish. I just used that with which I am familiar.)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 5:39









        ikegami

        260k11174394




        260k11174394






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236211%2fperl-regex-convert-multiple-decimal-numbers-on-a-line-to-nearest-integer%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Schultheiß

            Verwaltungsgliederung Dänemarks

            Liste der Kulturdenkmale in Wilsdruff