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

I have a doubt regarding one of my specific requirement and do't know how to proceed. I have some 6 field say field 1,field 2,field 3,field 4,field 5,field 6. When value for any field is entered its bit will set to 1 otherwise 0 and depend upon value entered or not i have to generate binary value. suppose field 1=Some value then it will be 1 field 2=blank then it will be 0 and output will be like this 1111 1100 if value for all fields are entered. Please help
  • Comment on How to get binary value based on field value entered

Replies are listed 'Best First'.
Re: How to get binary value based on field value entered
by Athanasius (Archbishop) on Jun 06, 2013 at 03:41 UTC
      Thanks for quick reply. This forum is best forum for any perl related queries.and you peoples are very helpful.
Re: How to get binary value based on field value entered
by BrowserUk (Patriarch) on Jun 06, 2013 at 03:57 UTC
    I have some 6 field say field 1,field 2,field 3,field 4,field 5,field 6.

    You'll have to clarify what you mean by "field"?

    Are these substrings within a single string? Or entryfields within an HTML form? Columns in a CSV file?

    And also what you mean by "blank"?

    Let's say that you have captured the fields into an array, then you might build you binary value this way:

    my @fields = ... ; my $binary = chr(0); defined( $fields[ $_ ] ) && length( $fields[ $_ ] ) and vec( $binary, +$_, 1 ) = 1 for 0 .. $#fields;

    For example:

    @fields = ( 'fred', undef, '', 0, 123, ' ' );; $binary = '';; vec( $binary, $_, 1 ) = ($fields[ $_ ] // '' ) =~ /\S/ ? 1 : 0 for 0 . +. $#fields;; print unpack 'b*', $binary;; 10011000

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: How to get binary value based on field value entered
by hdb (Monsignor) on Jun 06, 2013 at 07:23 UTC

    Here is another solution based on map and join:

    use strict; use warnings; my @fields = ( 1, "", undef, "0", "blah", 5 ); my $output = join "", map { length($_) ? 1 : 0 } @fields[0..7]; print "$output\n";

    map allows you to apply the test for a field being blank to each element of your fields array. I have used length but you can plug in any other test you deem appropriate. map will in this case return an array of 0s and 1s which is then joined into a string.

    From your question it seems that you want to get an answer of length 8, so I have expanded @fields by two (blank) fields using @fields[0..7]. If I mis-read this part of your question, just remove the [0..7] bit.